![](/img/trans.png)
[英]Laravel 7: Service provider bind a class with a constructor parameter model
[英]bind abstract class service in provider laravel
給出一個錯誤:
目標 [MyVendor\\ProductList\\ProductServiceInterface] 不可實例化。
產品服務接口
namespace MyVendor\ProductList;
interface ProductServiceInterface
{
public function productList();
public function getProductSpeed();
}
產品顏色服務
namespace MyVendor\ProductList\Service;
abstract class ProductColorService implements \MyVendor\ProductList\ProductServiceInterface
{
public function productList()
{
$color = "black";
return $color;
}
}
** 產品速度服務 **
namespace MyVendor\ProductList\Service;
abstract class ProductSpeedService implements \MyVendor\ProductList\ProductServiceInterface {
public function getProductSpeed() {
$speed = 200;
return $speed;
}
}
提供者:
namespace MyVendor\ProductList;
use Illuminate\Support\ServiceProvider;
use MyVendor\ProductList\ProductServiceInterface;
use MyVendor\ProductList\Service\ProductColorService;
class ProductColorServiceProvider extends ServiceProvider
{
public function boot()
{
$this->loadRoutesFrom(__DIR__ . '/routes/color.php');
}
public function register()
{
$this->app->bind('MyVendor\ProductList\ProductServiceInterface','MyVendor\ProductList\Service\ProductColorService');
$this->app->bind('MyVendor\ProductList\ProductServiceInterface','MyVendor\ProductList\Service\ProductSpeedService');
}
}
這段代碼有什么問題? 實際上我需要使用服務覆蓋界面中的一些功能。 即每個服務應該覆蓋一個方法。
namespace MyVendor\ProductList\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use MyVendor\ProductList\Models\Product;
use MyVendor\ProductList\ProductServiceInterface;
class ProductListController extends Controller
{
public function index(ProductServiceInterface $product_service)
{
$color = $product_service->productList();
$speed = $product_service->getProductSpeed();
dd($color," = ",$speed);
$product = Product::get();
return view('ProductList::product',compact('product'));
}
}
這里是一個服務中的productList()
和另一個服務中的productSpeed()
你不能實例化抽象類。 它們的重點是永遠不會有它們的實例,所以如果你用一個方法將你的接口綁定到你的抽象類,它就永遠不可能是抽象的。 Abstract 用於繼承結構中的類,您不希望用戶創建new
類。
所以沒有理由抽象,抽象是為了這樣的東西。
abstract class Vehicle {
protected $wheels;
public function getWheels() {
return $this->wheels;
}
}
class Car extends Vehicle {
protected $wheels = 4;
}
class Bike extends Vehicle {
protected $wheels = 2;
}
你不能制造車輛,因為它不是一個具體的實現,因為它是一個父類,用於幫助兩個類共享方法。 如此簡短的版本,只需刪除抽象關鍵字。 如果您不知道為什么要添加它,則不需要它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.