Laravel5 dependency injection on Model

懵懂的女人 提交于 2019-12-09 15:29:04

问题


I have an Eloquent Model called Surface which is dependent on a ZipCodeRepository object:

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

and an Address object that hasMany surfaces.

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

My issue is when I call $address->surfaces I get the following error:

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

I thought the IoC would automatically inject that.


回答1:


Thanks to @svmm for referencing the question mentioned in the comments. I found that you cannot use dependency injection on Models because you would have to change the signature on the constructor which doesn't work with the Eloquent framework.

What I did as an intermediate step, while refactoring the code, is use App::make in the constructor to create the object, such as:

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

That way the IoC will still grab the implemented repository. I am only doing this until I can pull the functions into the repository to remove the dependency.




回答2:


In Laravel 5.7 you can use the global resolve(...) method. I don't think the global App is defined in more recent version of Laravel.

$myService = resolve(ServiceName::class);

Resolving in Laravel docs



来源:https://stackoverflow.com/questions/33636880/laravel5-dependency-injection-on-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!