2013-03-13 60 views
2

services.xml文件:Symfony的2註冊一個學說聽者不工作

<?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不被堅持之後調用任何想法?

回答

2

您在混合事件訂閱者和事件偵聽器!

我會去一個事件偵聽器:

刪除

implements EventSubscriber 

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

請確保您使用

use Doctrine\ORM\Event\LifecycleEventArgs; 

和中聲明。得到加載到src/Acme/Bu中ndle/DependencyInjection/AcmeExtension.php。

清除緩存,它應該工作。

的官方文檔可以在 http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html

+1

只是爲了您的信息:任何用戶也是一個有效的監聽器 - 請參閱https://github.com/doctrine/common/blob/2.3.0 /lib/Doctrine/Common/EventManager.php#L126-L135 – Ocramius 2013-03-13 12:30:05

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> 
0

當你想實現EventListener - 你應該在命名監聽器類的方法完全一樣的事件。在你的例子中 - 你應該有一個名爲postPersist的公共方法。偵聽器類不應該實現EventSubscriber。 有一個鏈接,可以讓你更清楚地瞭解這個主題http://docs.doctrine-project.org/en/latest/reference/events.html

+0

請不要參考'2.0.x'文檔。使用'latest'代替:docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html – Ocramius 2013-03-13 12:30:48

+0

我沒有downvote你的答案:)我只是想讓你意識到事實你應該總是參考最新的文檔。這有很大幫助! – Ocramius 2013-03-13 13:41:59