本文介绍了Laravel5对模型的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为Surface的口才模型,它依赖于ZipCodeRepository对象:

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

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

和具有许多表面的Address对象.

and an Address object that hasMany surfaces.

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

我的问题是,当我致电$address->surfaces时,出现以下错误:

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

我认为IoC会自动注入.

I thought the IoC would automatically inject that.

推荐答案

感谢@svmm引用.我发现您无法在模型上使用依赖项注入,因为您将不得不更改不适用于Eloquent框架的构造函数上的签名.

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.

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

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');
    }

这样,IoC仍将获取已实现的存储库.我只是在这样做,直到可以将功能拉入存储库中以删除依赖项为止.

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.

这篇关于Laravel5对模型的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:34