JakubD
JakubD

Reputation: 93

How to inject service into factory created object in Symfony

I have custom class EmailNotifier which is created inside a factory class NotifierFactory. I need to use the Mailer service inside the EmailNotifier. But how to inject the service inside? It can't be injected into constructor, because I'm creating the class in this way:

$emailNotifier = new EmailNotifier();

I tried to inject it in services.yaml

App\Service\Notifier\Notifiers\EmailNotifier:
 calls:
    - [setMailer, ['@mailer']]

but the method setMailer() is never called.

Upvotes: 0

Views: 1384

Answers (2)

Ihor Kostrov
Ihor Kostrov

Reputation: 2561

You also can inject mailer to NotifierFactory constructor via service container and in your factory do something like this:

$emailNotifier = (new EmailNotifier())->setMailer($this->mailer);

Update: maybe useful in your case https://symfony.com/doc/current/service_container/factories.html

Upvotes: 0

JakubD
JakubD

Reputation: 93

If I choose another approach, I can inject services to my "notifiers"

# Defining each notifier as a service, then pass another service inside (mailer here)
notifiers.email:
    public: true
    class: App\Service\Notifier\Notifiers\EmailNotifier
    calls:
        - [setMailer, ['@mailer']]

# Pass each notifier service inside the Notifier object, which replaces the factory class
App\Service\Notifier\Notifier:
    calls:
        - [setNotifierServices, ['@notifiers.email']]

Upvotes: 1

Related Questions