2

我已经创建了自定义事件,例如当用户被生成时,事件调度程序将触发该事件。

我正在关注本教程。我想知道他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呢?

4

1 回答 1

8

侦听器是普通服务。您可以将其与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

于 2012-08-02T05:21:56.903 回答