Laravel ::__construct() 必须实现接口

延森

我正在使用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班正在实施OrderRepositoryInterfaceOrder 类正在实现该OrderInterface接口。

App\Forum 是使用Orderabletrait的模型

我在这里做错了什么?

您正在扩展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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Laravel Passport TokenGuard :: __ construct()必须实现接口

__construct()必须实现接口错误

绑定接口问题:传递给__construct()的参数1必须实现接口

Laravel 5 Auth:用户必须实现CanResetPassword接口

可捕获的致命错误:传递给“ ... \ FormType :: __ construct()的参数1必须实现接口

Symfony2:ContextErrorException:可捕获的致命错误:传递给[...] :: __ construct()的参数1必须实现接口[...]

传递给 Illuminate\Auth\SessionGuard::__construct() 的参数 2 必须实现接口 Illuminate\Contracts\Auth\UserProvider,给出 null

雄辩的Laravel模型的__construct

使用数据库提供程序在 Laravel 项目上开箱即用地重置密码:“用户必须实现 canresetpassword 接口”

如何在Laravel中测试接口的实现

laravel,如何向函数 __construct() 添加条件

指定 Class 参数必须实现特定接口

Java:类型参数必须实现接口

Encoder-> IsPasswordValid必须实现\ UserInterface接口

count()参数必须是在laravel中实现可计数的数组或对象

count():参数必须是在Laravel 6中实现Countable的数组或对象

count():参数必须是数组或者实现了Countable的对象(laravel报错)

如何在PHP(Laravel)中使用接口的多种实现?

在Laravel中登录后将接口绑定到实现

如何观察在Laravel 5.1中实现接口的所有模型?

不确定Laravel对接口实现做了什么

Typescript 接口数组必须实现一个基本接口

Laravel 5.3 Controller __construct在中间件之前调用

Laravel:参数2传递给Illuminate \ Auth \ SessionGuard :: __ construct()

laravel 5.4:无法在__construct方法中访问Auth :: user()

无法在 laravel 测试单元中的 __construct 填充属性

Laravel 7 __construct中的用户数据

Laravel 5.4:在__construct()中获取登录用户ID

Laravel接口