如果我在symfony2中创建自定义事件,我如何访问实体管理器 [英] How can i access entity manager if i create custom event in symfony2

查看:104
本文介绍了如果我在symfony2中创建自定义事件,我如何访问实体管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了自定义事件,就像当用户被分类时,事件调度员将触发该事件。

I have created custom event like when user is generataed then Event dispatcher will fire that event.

我正在关注本教程。我想知道在他的 class CommentListener 中,我如何访问实体管理器,因为我想在数据库中保留很少的东西。

I am following this tutorial. I want to know that in his class CommentListener how can I access the entity manager because I want to persist few things in the database.

类是这样的:

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

So how can I access entity manager inside onCommentEvent?

推荐答案

听众是正常的服务。您可以将其注入构造函数以及 mailer 。以下这些行:

Listeners are normal services. You can just inject it into constructor along with mailer. Something along these lines:

服务:

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

If you ever need to find out name of certain service run php app/console container:debug.

这篇关于如果我在symfony2中创建自定义事件,我如何访问实体管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆