Laravel5 model dependency injection

I have an Eloquent Model called Surface, which depends on the ZipCodeRepository object:

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

and an Address object that has many surfaces.

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

My problem is that 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 IoC would automatically add this.

+5
source share
1 answer

Thanks to @svmm for linking to the question mentioned in the comments . I found that you cannot use dependency injection for models because you have to change the signature on a constructor that does not work with the Eloquent framework.

What I did as an intermediate step in refactoring the code was using App::make in the constructor to create the object, for example:

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

Thus, IoC will still capture the implemented repository. I only do this until I can pull the functions into the repository to remove the dependency.

+12
source

Source: https://habr.com/ru/post/1235631/


All Articles