2

服务.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 在坚持后没有被调用的任何想法?

4

3 回答 3

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>
于 2013-03-13T07:19:27.090 回答
2

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

我会去找一个事件监听器:

消除

implements EventSubscriber

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

确保你使用

use Doctrine\ORM\Event\LifecycleEventArgs;

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

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

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

于 2013-03-13T07:15:16.423 回答
0

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

于 2013-03-13T10:14:20.740 回答