我正在使用symfony 3.2.7,并希望将通过应用程序发送的每一封电子邮件的信息(使用Swift Mailer)存储在我的数据库中。我正在尝试使用EventSubscriber来执行此操作,因为在成功发送电子邮件后,Swift Mailer会从RESULT_SUCCESS
类派发一个Swift_Events_SendEvent
常量。但这是行不通的。
发送邮件时肯定会处理包含EventSubscriber的文件(为了测试,我故意在文件中添加了错误的语法,并且在发送邮件时收到语法错误),但是onMailSent
函数显然没有被调用,因为电子邮件信息没有存储在我的数据库中。而且该功能可以在其他上下文中使用,因此问题不在于功能本身。
我在做什么错?这是我的代码:
SentMailsListener.php:
<?php
namespace Fidelise\SignUpBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Fidelise\SignUpBundle\Entity\EmailsHistory;
use Swift_Events_SendEvent;
class SentMailsListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [Swift_Events_SendEvent::RESULT_SUCCESS => 'onMailSent'];
}
public function onMailSent(Swift_Events_SendEvent $event)
{
$em = $this->getDoctrine()->getManager();
$message = $event->getMessage();
$email = new EmailsHistory();
$email->setRecipient(key($message->getTo()));
$email->setSubject($message->getSubject());
$email->setBody($message->getBody());
$email->setSender(key($message->getFrom()));
$em->persist($email);
$em->flush();
}
}
services.yml:
services:
mail_sent_subscriber:
class: Fidelise\SignUpBundle\EventListener\SentMailsListener
tags:
- { name: kernel.event_subscriber }
答案 0 :(得分:3)
应该做的是注册swiftmailer插件。它不是事件调度程序的事件侦听器:
<?php
namespace Fidelise\SignUpBundle\EventListener;
use Swift_Events_SendEvent;
use Swift_Events_SendListener;
class SentMailsListener implements Swift_Events_SendListener
{
public function sendPerformed(Swift_Events_SendEvent $event): void
{
// ...
}
}
services:
mail_sent_subscriber:
class: Fidelise\SignUpBundle\EventListener\SentMailsListener
tags:
- { name: swiftmailer.default.plugin }