2016-01-21 33 views
0

我有一個看起來像一個ExampleListener類:調度員不分派我的事件的symfony

<?php 

namespace AppBundle\EventListener; 

class ExampleListener 
{ 
    public function helloWorld() 
    { 
     echo "Hello World!"; 
    } 
} 

這是我services.yml

services: 
    my.event: 
     class: AppBundle\EventListener\ExampleListener 
     tags: 
      - { name: kernel.event_listener, event: my.event, method: helloWorld } 

然後從控制器我試圖派遣事件。

$dispatcher = new EventDispatcher(); 
$dispatcher->dispatch('my.event') 

我沒有任何錯誤,但helloWorld函數永遠不會調用。 我的事件達:

PHP斌/控制檯調試:事件調度my.event

結果是:

#1  AppBundle\EventListener\ExampleListener::helloWorld() 0 

爲什麼調度好好嘗試一下正確調用事件? 謝謝。

+2

你需要使用容器已經實例化的事件分派器。嘗試'$這個 - >容器 - >獲取( 'event_dispatcher') - >訊( 'my.event');' – qooplmao

+0

你可以在這裏找到例如:http://stackoverflow.com/a/34162603/3612353 –

回答

1

您已經創建了一個新的事件分派器,它與Symfony用於註冊您在容器配置中定義的事件偵聽器不同。

而不是創建事件調度自己的,使用已經由Symfony的定義的。您可以從容器中的控制器讀取它,例如:

$this->container->get('event_dispatcher')->dispatch('my.event'); 

如果您需要從服務調度的情況下,簡單地將event_dispatcher服務爲一體的構造函數的參數之一:

services: 
    my_service: 
     class: Foo\MyService 
     arguments: 
      - @event_dispatcher