Inject SwiftMailer into symfony2 service
Asked Answered
P

2

12

I have a service which extends UserManager, so when I do:

$message = \Swift_Message::newInstance()
            ->setSubject('~')
            ->setFrom('~')
            ->setTo('~')
            ->setBody('~', 'text/html');
        $this->get('mailer')->send($message);

I get the error:

Fatal error: Call to undefined method My\MyBundle\Service\ServiceClass::get()

I know this is because I need to inject the swiftmailer into here, but how? (usually the service class extends 'Generic' so the swift mailer is included.)

Pignus answered 16/1, 2013 at 14:53 Comment(0)
S
21

Depending on what kind of service file you are using you need to inject it into your service directly like you said.

XML:

<services>
        <service id="sample.service" class="%sample.service.class%">
            <argument type="service" id="mailer" />
        </service>
</services>

YAML:

services:
    sample.service:
        class:     %sample.service.class%
        arguments: [@mailer]

You can simply grab the service in your constructor like this. Or if you really want, you can inject the service_container. But that's really dirty, since you can just inject the services you need.

Injection the service_container is only needed if you need a dynamic service call.

Savona answered 16/1, 2013 at 15:0 Comment(3)
I have added the service in the .yml file but I'm not sure how to call it in in the constructor of the class?Pignus
Simply add a parameter to the constructor, like public function __construct($mailer) and then e.g. assign it to a private property in the constructor body.Correction
a dummys guide: Add the service as answer above. Then add to the constructor as above comment. then add $this->mailer = $mailer; in the constructor. You can then use: $this->mailer->send($message);Pignus
D
1

In services.yml (symfony 4 example)

mailer:
    class: \Swift_Mailer

myClass:
    class: x\x
    arguments:
        - "@mailer"
Diaphane answered 19/4, 2019 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.