我正在使用Laravel 5.4
并且我正在尝试将一个$order
类注入trait
到将由model
. 像这样:
class Forum extends Model
{
use Orderable;
该constructor
性状看起来像这样的:
trait Orderable
{
public $orderInfo;
public function __construct(OrderInterface $orderInfo)
{
$this->orderInfo = $orderInfo;
}
我的服务提供商看起来像这样:
public function register()
{
$this->app->bind(OrderInterface::class, function () {
return new Order(new OrderRepository());
});
$this->app->bind(OrderRepositoryInterface::class, function () {
return new OrderRepository();
});
}
我的Order
类的构造函数如下所示:
public function __construct(OrderRepositoryInterface $orderInfo)
{
$this->orderInfo = $orderInfo;
}
但我收到错误:
Type error: Argument 1 passed to App\Forum::__construct() must implement interface Project\name\OrderInterface, array given, called in /home/vagrant/Code/Package/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 268
该OrderRepository
班正在实施OrderRepositoryInterface
。Order 类正在实现该OrderInterface
接口。
App\Forum 是使用Orderable
trait的模型。
我在这里做错了什么?
您正在扩展Model
. 这个类已经有一个__construct
你需要使用的。这__construct
期望array $attributes = []
作为第一个参数。
因此,您__construct
还需要将此作为第一个参数并将其传递给父类:
public function __construct(array $attributes = [], OrderRepositoryInterface $orderInfo)
{
$this->orderInfo = $orderInfo;
parent::__construct($attributes);
}
但是,您可以__construct
使用boot
.
例如在一个Model
:
class Forum extends Model
{
protected static function boot()
{
parent::boot();
// Do something
}
}
或者在一个Trait
:
trait Orderable
{
public static function bootOrderableTrait()
{
static::created(function($item){
// Do something
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句