Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject SwiftMailer into symfony2 service

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.)

like image 844
Andrew Atkinson Avatar asked Jan 16 '13 14:01

Andrew Atkinson


2 Answers

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.

like image 156
Schwierig Avatar answered Sep 29 '22 14:09

Schwierig


In services.yml (symfony 4 example)

mailer:
    class: \Swift_Mailer

myClass:
    class: x\x
    arguments:
        - "@mailer"
like image 41
Smith Avatar answered Sep 29 '22 15:09

Smith