Jimit
Jimit

Reputation: 2259

How constructor dependency injection works in Laravel?

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.

Upvotes: 3

Views: 2754

Answers (1)

Matthieu Napoli
Matthieu Napoli

Reputation: 49623

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.

Upvotes: 12

Related Questions