2013-04-05 94 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