3

I am using Laravel. I knew we can write constructor dependency injection as below code. I am wondering how it is working? I mean how constructor get $post and $user model objects? How it is injected?

    /**
     * Inject the models.
     * @param Post $post
     * @param User $user
     */
    public function __construct(Post $post, User $user)
    {
        parent::__construct();

        $this->post = $post;
        $this->user = $user;
    }

Please explain me. Thanks.

2
  • because __construct(Post $post , $post is type of Post then create a Post object and assign to $post Commented Dec 15, 2014 at 5:52
  • 1
    How it will find Post class and create it's object? Commented Dec 15, 2014 at 6:23

1 Answer 1

12

Laravel IoC uses a process called Autowiring. This is something that is very common in other languages and other PHP IoC containers.

The idea is to look at the constructor parameters using PHP's Reflection API. Using that, Laravel can see that $post needs to be a Post instance and thus it will create it on the fly. In short, Laravel will do something like this:

$post = new Post();
$user = new User();
$obj = new TheClass($post, $user);

(if you wonder how it will find the Post class: the Composer autoloader will autoload it based on your configuration in composer.json)

This process works well with Services (i.e. "utility" classes like the Database, Logger, etc.) but it doesn't work with Model classes.

The reason for this is simple: Laravel can't know which post and user you want to inject (assuming there are several in your database). Instead you should fetch those instances from the database and pass them around yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Matthieu to explain me. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.