我已经创建了自定义事件,比如当生成用户时,事件调度程序将触发该事件。
我正在学习本教程。我想知道,在他的class CommentListener
中,我如何访问实体管理器,因为我想在数据库中保留一些东西。
类是这样的:
class CommentListener
{
protected $mailer;
public function __construct(Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function onCommentEvent(CommentEvent $event)
{
$post = $event->getPost();
$comment = $event->getComment();
foreach ($post->getSubscribers() as $subscriber) {
$message = Swift_Message::newInstance()
->setSubject('New comment posted on ' . $post->getTitle())
->setFrom('send@example.com')
->setTo($subscriber->getEmail())
->setBody("Hey, somebody left a new comment on a post you're subscribed to! It says: " . $comment->getBody())
;
$this->mailer->send($message);
}
}
}
那么,我如何访问onCommentEvent
内部的实体管理器呢?
监听器是正常的服务。您可以将它与mailer
一起注入构造函数。大致如下:
服务:
services:
foo_bundle.listener.comment:
class: FooVendorBarBundleEventListenerCommentListener
arguments:
mailer: "@mailer"
entityManager: "@doctrine.orm.entity_manager"
tags:
- { name: kernel.event_listener, event: foo_bundle.post.comment_added, method: onCommentEvent }
侦听器类:
class CommentListener
{
protected $mailer;
protected $entityManager;
public function __construct(Swift_Mailer $mailer, $entityManager)
{
$this->mailer = $mailer;
$this->entityManager = $entityManager;
}
...
如果您需要查找某个服务的名称,请运行php app/console container:debug
。