2013-04-05 91 views
5

我有一個包含兩個程序的程序。其中一個(CommonBundle)發送一個事件「common.add_channel」,而另一個(FetcherBundle)上的服務應該正在監聽它。在探查器上,我可以在「未調用的偵聽器」部分中看到事件common.add_channel。我不明白爲什麼symfony沒有註冊我的聽衆。爲什麼symfony2不會調用我的事件偵聽器?

這是我的動作,裏面CommonBundle\Controller\ChannelController::createAction

$dispatcher = new EventDispatcher(); 
$event = new AddChannelEvent($entity);   
$dispatcher->dispatch("common.add_channel", $event); 

這是我AddChannelEvent

<?php 

namespace Naroga\Reader\CommonBundle\Event; 

use Symfony\Component\EventDispatcher\Event; 
use Naroga\Reader\CommonBundle\Entity\Channel; 

class AddChannelEvent extends Event { 

    protected $_channel; 

    public function __construct(Channel $channel) { 
     $this->_channel = $channel; 
    } 

    public function getChannel() { 
     return $this->_channel; 
    } 

} 

這應該是我的聽衆(FetcherService.php):

<?php 

namespace Naroga\Reader\FetcherBundle\Service; 

class FetcherService { 

    public function onAddChannel(AddChannelEvent $event) { 
     die("It's here!");  
    } 
} 

這裏是我註冊我的聽衆(services.yml)的地方:

kernel.listener.add_channel: 
    class: Naroga\Reader\FetcherBundle\Service\FetcherService 
    tags: 
     - { name: kernel.event_listener, event: common.add_channel, method: onAddChannel } 

我在做什麼錯?爲什麼當我派遣common.add_channel時symfony不會調用事件監聽器?

+0

標準symfony問題:在services.yml中添加監聽器之後是否清除了緩存? – 2013-04-05 20:24:08

+0

是的。並非如此,如果您在每個pagehit上使用app_dev.php,那麼services.yml的任何更改都會重新編譯到緩存。不過,我已經清理了很多次。 – 2013-04-08 17:37:08

回答

12

新事件調度程序不知道關於另一個調度程序上設置的監聽器的任何信息。

在您的控制器中,您需要訪問event_dispatcher服務。框架包的編譯器通道將所有監聽器附加到該調度器。要獲得服務,請使用Controller#get()快捷鍵:

// ... 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class ChannelController extends Controller 
{ 
    public function createAction() 
    { 
     $dispatcher = $this->get('event_dispatcher'); 
     // ... 
    } 
} 
+0

就是這樣。謝謝:) – 2013-04-08 17:37:26

+0

謝謝,幫幫我吧 – 2013-09-09 18:19:45

+0

這個在Symfony 2.3.4中還能工作嗎?或者有這個改變? – Chausser 2013-10-02 22:31:42

相關問題