Laravel5 dependency injection on Model

前端 未结 2 1819
深忆病人
深忆病人 2021-02-13 15:10

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

class Surface extends Model{
    public function __construct(ZipCodeRep         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-13 15:34

    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.

提交回复
热议问题