2015-11-10 52 views
5

我有一个锋模型称为表面这取决于一个ZipCodeRepository对象上:Laravel5依赖注入上模型

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

和一个地址对象的hasMany表面。

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 

我认为国际奥委会将自动注入这一点。

+0

看这里:https://stackoverflow.com/questions/22338161/cant-pass-class-instance-to-constructor/22338753 ...特别是在github上打开的问题 – svrnm

回答

12

感谢@svmm引用the question mentioned in the comments。我发现你不能在模型上使用依赖注入,因为你必须改变构造函数的签名,这个签名不能和Eloquent框架一起工作。

我做了作为一个中间步骤是什么,而重构代码,是用App::make在构造函数来创建对象,如:

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

这样的国际奥委会将仍然抢来实现存储库。我只能这样做,直到我可以将函数拉入存储库以删除依赖项。

+0

谢谢!当传递一个依赖到Model构造函数时,执行一个Eloquent查找(id)时,我得到了“太少的参数”错误。这种方法效果更好 – Stetzon