Gonçalo Marrafa
Gonçalo Marrafa

Reputation: 2113

Laravel setter injection

How can i use setter dependency injection with Laravel's service container to have automatic dependency resolution?

Here's an example:

class Test
{
    (...)

    public function setMailer(Mailer $mailer) 
    {
        $this->mailer = $mailer;
    }

    (...)

    function sendEmail()
    {
        $this->mailer->send(new Email('[email protected]'));
    }
}

How can i ensure that, when sendEmail() is called, the mailer dependency is statisfied? How can i leverage Laravel's service container to achieve this?

Thanks in advance.

Upvotes: 4

Views: 2006

Answers (1)

lagbox
lagbox

Reputation: 50481

There is no way for you to ensure that other method is ran before sendEmail is ran and the only method that could have 'method injection' would be setMailer.

If you wanted method injection for the setMailer method you would have to use the IoC container to call that method:

$a = new Test;
app()->call([$a, 'setMailer']);

This will have the container call setMailer on $a for you and will resolve any dependencies needed, in this case.

Having the container call sendEmail would be exactly the same as calling it yourself, as there are no arguments.

If you really wanted a mailer to be available, you could use constructor injection so you have the mailer before sendEmail is called.

public function __construct(Mailer $mailer)
{
    $this->mailer = $mailer;
}

Upvotes: 3

Related Questions