Symfony2 - Doctrine/ORM 上的监听器

4
在Symfony2 / Doctrine中,记录插入后触发事件的最佳方式是什么?
2个回答

10

首先,将一个服务注册为Doctrine事件监听器:

app/config.yml:

services:
    foo.listener:
        class: Vendor\FooBundle\BarClass
        tags:
            - { name: doctrine.event_listener, event: postPersist, method: onPostPersist }

然后在您的监听器类中,定义一个onPostPersist方法(或者在配置中命名的任何方法),该方法接受一个Doctrine\ORM\Event\LifecycleEventArgs参数:

public function onPostPersist(LifecycleEventArgs $eventArgs)
{
    // do stuff with the entity here
}

注意,你不能将EntityManager的实例传递给监听器类,因为$eventArgs包含对它的引用,这样做会抛出CircularReferenceException异常。
Doctrine项目文档这里。Symfony项目文档这里(已过时,但供参考)。

我正在做完全相同的事情,但是我试图在我的监听器中包含对securityContext对象的引用。我在我的yml文件中添加了:arguments: ["@security.context"],但是当我将$securityContext对象添加到我的构造函数中时,我会收到循环引用错误。有什么想法吗?我正在使用FOSUserBundle,并且在我收到的错误中显示出来。 - Jeremy
1
这是我收到的错误。ServiceCircularReferenceException:检测到服务“security.context”循环引用,路径:“profiler_listener -> profiler -> security.context -> security.authentication.manager -> fos_user.user_manager -> doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> my.listener”。 - Jeremy

1
尝试注入容器本身而不是安全上下文。对于FOS_USER,security.context取决于您的侦听器(EM),而您的侦听器需要security.context。
<service id="foo.listener" class="%foo.listener.class%">
  <argument type="service" id="service_container"/>
  <tag name="doctrine.event_listener" event="postPersist" method="fooMethod" />
</service>

顺便说一下,在XML中,方法名似乎不起作用,默认调用方法'postPersist',忽略您给出的任何方法名(fooMethod); 如果YAML配置也是这种情况,请告诉我,否则我就错了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接