Symfony 2注册了一个不起作用的学说监听器

时间:2013-03-13 06:45:52

标签: symfony doctrine-orm doctrine

Services.xml文件:

<?xml version="1.0" ?>

    <container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">  

        <services>
            <service id="task.task_history_insertion" class="Acme\Bundle\EventListener\TaskHistoryInsertion">
                <argument type="service" id="service_container" />
                <tag name="doctrine.event_listener" event="postPersist" method="postPersist"/>
            </service>
        </services>
    </container>

TaskHistoryInsertion.php

class TaskHistoryInsertion implements EventSubscriber
{

    protected $container;
public function __construct(ContainerInterface $container)
{
    $this->container = $container; 
}

public function getSubscribedEvents()
{
    return array(
        Event::postPersist
    );
}

public function postPersist(LifecycleEventArgs $args)
{
         //not being called
        }
}

关于为什么postPersist在持久化后没有被调用的任何想法?

3 个答案:

答案 0 :(得分:3)

确保为您的服务使用正确的标记。您需要使用doctrine.event_subscriber

<service id="task.task_history_insertion" class="Acme\Bundle\EventListener\TaskHistoryInsertion">
    <argument type="service" id="service_container" />
    <tag name="doctrine.event_subscriber"/>
</service>

答案 1 :(得分:2)

您正在混合事件订阅者和事件监听器!

我会选择一个事件监听器:

删除

implements EventSubscriber

public function getSubscribedEvents()
{
    return array(
        Event::postPersist
    );
}

确保使用

use Doctrine\ORM\Event\LifecycleEventArgs;

并且在src / Acme / Bundle / DependencyInjection / AcmeExtension.php中加载了services.xml。

清除缓存,它应该可以正常工作。

官方文档可在以下网址找到: http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html

答案 2 :(得分:0)

当您想要实现eventListener时 - 您应该在侦听器类中将该方法命名为与事件完全相同。在您的示例中 - 您应该使用名为postPersist的公共方法。并且监听器类不应该实现EventSubscriber。 有一个链接可以让您更清楚地了解此主题http://docs.doctrine-project.org/en/latest/reference/events.html