将SwiftMailer注入symfony2服务
我有一个扩展UserManager的服务,因此当我这样做时:将SwiftMailer注入symfony2服务,symfony,dependency-injection,swiftmailer,Symfony,Dependency Injection,Swiftmailer,我有一个扩展UserManager的服务,因此当我这样做时: $message = \Swift_Message::newInstance() ->setSubject('~') ->setFrom('~') ->setTo('~') ->setBody('~', 'text/html'); $this->get('mailer')->send($m
$message = \Swift_Message::newInstance()
->setSubject('~')
->setFrom('~')
->setTo('~')
->setBody('~', 'text/html');
$this->get('mailer')->send($message);
我得到一个错误:
Fatal error: Call to undefined method My\MyBundle\Service\ServiceClass::get()
我知道这是因为我需要把速递器注射到这里,但是怎么注射呢?
(通常服务类扩展了“Generic”,因此包含了swift-mailer。)根据您使用的服务文件类型,您需要像您所说的那样将其直接注入到您的服务中 XML: 您可以像这样简单地在构造函数中获取服务。 或者,如果确实需要,可以插入
服务\u容器
。但是这真的很糟糕,因为你可以只注入你需要的服务
只有在需要动态服务调用时才需要使用服务容器。在services.yml中(symfony 4示例)
我已经在.yml文件中添加了服务,但我不确定如何在类的构造函数中调用它?只需向构造函数中添加一个参数,如公共函数\uu构造($mailer)
,然后将其分配给构造函数体中的私有属性。dummys指南:按照上面的答案添加服务。然后添加到构造函数中,如上面的注释所示。然后添加$this->mailer=$mailer构造函数中的代码>。然后可以使用:$this->mailer->send($message)代码>
<services>
<service id="sample.service" class="%sample.service.class%">
<argument type="service" id="mailer" />
</service>
</services>
services:
sample.service:
class: %sample.service.class%
arguments: [@mailer]
mailer:
class: \Swift_Mailer
myClass:
class: x\x
arguments:
- "@mailer"