2013-08-28 45 views
9

我正在嘗試基於此處給出的示例 - http://symfony.com/doc/master/components/event_dispatcher/introduction.html設置一個簡單的事件訂閱。Symfony2事件訂戶不會調用偵聽器

這裏是我的事件存儲:

namespace CookBook\InheritanceBundle\Event; 

final class EventStore 
{ 
    const EVENT_SAMPLE = 'event.sample'; 
} 

這裏是我的事件訂閱:

namespace CookBook\InheritanceBundle\Event; 

use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\EventDispatcher\Event; 

class Subscriber implements EventSubscriberInterface 
{ 
    public static function getSubscribedEvents() 
    { 
     var_dump('here'); 
     return array(
       'event.sample' => array(
         array('sampleMethod1', 10), 
         array('sampleMethod2', 5) 
       )); 
    } 

    public function sampleMethod1(Event $event) 
    { 
     var_dump('Method 1'); 
    } 

    public function sampleMethod2(Event $event) 
    { 
     var_dump('Method 2'); 
    } 
} 

下面是services.yml的配置:

kernel.subscriber.subscriber: 
    class: CookBook\InheritanceBundle\Event\Subscriber 
    tags: 
     - {name:kernel.event_subscriber} 

這裏就是我如何引發事件:

use Symfony\Component\EventDispatcher\EventDispatcher; 
use CookBook\InheritanceBundle\Event\EventStore; 
$dispatcher = new EventDispatcher(); 
$dispatcher->dispatch(EventStore::EVENT_SAMPLE); 

預期輸出:

string 'here' (length=4) 
string 'Method 1' (length=8) 
string 'Method 2' (length=8) 

實際輸出:

string 'here' (length=4) 

出於某種原因,聽者方法不會被調用。任何人都知道這段代碼有什麼問題?謝謝。

回答

7

您可以嘗試注入配置EventDispatcher@event_dispatcher),而不是instanciating一個新的(new EventDispatcher

如果你只是創建它,並添加一個事件偵聽器的Symfony仍然沒有提及這個新創建的EventDispatcher對象並不會使用它。

如果你是一個控制器誰伸出ContainerAware內:

use Symfony\Component\EventDispatcher\EventDispatcher; 
use CookBook\InheritanceBundle\Event\EventStore; 

... 

$dispatcher = $this->getContainer()->get('event_dispatcher'); 
$dispatcher->dispatch(EventStore::EVENT_SAMPLE); 

我已經適應我的回答感謝this question's answer即使兩個問題的背景是不同的,答案仍然適用。

+0

乾杯,特里斯坦。我需要重溫我在symfony中對依賴注入的理解。 – Prathap

+3

我看到你或多或少只是複製粘貼我的答案[這裏](http://stackoverflow.com/questions/17671825/how-to-take-advantage-of-kernel-terminate-inside-an-event-listener )到你自己的問題沒有在這裏引用它 - 請給原來的答覆下次:)一些功勞:) – nifr

+0

是的完全我沒有聯繫,因爲背景是不同的,對我來說,我已經在一個監聽器,所以我很害怕它會混淆事情。但是你的回答完全適用於這個問題。 –

8

@Tristan說了些什麼。服務文件中的標籤部分是Symfony Bundle的一部分,並且只有在您將調度程序從容器中拉出時纔會被處理。

你的榜樣會按預期工作,如果你這樣做:

$dispatcher = new EventDispatcher(); 
$dispatcher->addSubscriber(new Subscriber()); 
$dispatcher->dispatch(EventStore::EVENT_SAMPLE); 
+0

乾杯,Cerad。我一直在尋找來自配置文件的注入,這正是特里斯坦所提出的。 – Prathap

+2

我完全理解。 @Tristan值得信任。這更多的是記錄爲什麼它從容器中運行,而不是你的發佈代碼。 – Cerad

相關問題