Laravel5依赖注入模型

ajo*_*jon 10 ioc-container laravel-5

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

class Surface extends Model{
    public function __construct(ZipCodeRepositoryInterface $zipCode){...}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

我以为IoC会自动注入它.

ajo*_*jon 23

感谢@svmm引用评论中提到的问题.我发现您不能在模型上使用依赖注入,因为您必须更改构造函数上的签名,该签名不适用于Eloquent框架.

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

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

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


小智 7

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

$myService = resolve(ServiceName::class);
Run Code Online (Sandbox Code Playgroud)

在 Laravel 文档中解决