Laravel5依赖注入模型

问题描述 投票:10回答:2

我有一个名为Surface的Eloquent Model,它依赖于ZipCodeRepository对象:

class Surface extends Model{
    public function __construct(ZipCodeRepositoryInterface $zipCode){...}

和一个具有多个曲面的Address对象。

class Address extends Model{
    public surfaces() { return $this->hasMany('App/Surface'); }
}

我的问题是,当我调用$address->surfaces时,我收到以下错误:

Argument 1 passed to App\Surface::__construct() must be an instance of App\Repositories\ZipCodeRepositoryInterface, none given

我以为IoC会自动注入它。

laravel-5 ioc-container
2个回答
20
投票

感谢@svmm引用the question mentioned in the comments。我发现您不能在模型上使用依赖注入,因为您必须更改构造函数上的签名,该签名不适用于Eloquent框架。

我在重构代码时作为中间步骤所做的是在构造函数中使用App::make来创建对象,例如:

class Surface extends Model{
    public function __construct()
    {
        $this->zipCode = App::make('App\Repositories\ZipCodeRepositoryInterface');
    }

这样IoC仍然可以获取已实现的存储库。我只是这样做,直到我可以将函数拉入存储库以删除依赖项。


0
投票

在Laravel 5.7中,您可以使用全局resolve(...)方法。我不认为全球App是在更新版本的Laravel中定义的。

$myService = resolve(ServiceName::class);

Resolving in Laravel docs

© www.soinside.com 2019 - 2024. All rights reserved.