PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

[FIXED] Laravel5 dependency injection on Model

 February 16, 2022     ioc-container, laravel-5     No comments   

Issue

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.


Solution

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.



Answered By - ajon
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing