将SwiftMailer注入symfony2服务

And*_*son 11 dependency-injection swiftmailer symfony

我有一个扩展UserManager的服务,所以当我这样做时:

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

我收到错误:

Fatal error: Call to undefined method My\MyBundle\Service\ServiceClass::get()
Run Code Online (Sandbox Code Playgroud)

我知道这是因为我需要将swiftmailer注入这里,但是如何?(通常服务类扩展'Generic',因此包含了swift邮件程序.)

Sch*_*rig 20

根据您使用的服务文件类型,您需要像您所说的那样直接将其注入您的服务.

XML:

<services>
        <service id="sample.service" class="%sample.service.class%">
            <argument type="service" id="mailer" />
        </service>
</services>
Run Code Online (Sandbox Code Playgroud)

YAML:

services:
    sample.service:
        class:     %sample.service.class%
        arguments: [@mailer]
Run Code Online (Sandbox Code Playgroud)

您可以像这样简单地在构造函数中获取服务.或者,如果你真的想要,你可以注入service_container.但这真的很脏,因为你可以注入你需要的服务.

service_container只有在需要动态服务调用时才需要注入.

  • 只需在构造函数中添加一个参数,比如`public function __construct($ mailer)`,然后将其分配给构造函数体中的私有属性. (2认同)