为什么symfony2没有调用我的事件监听器?

Ped*_*iro 5 php symfony

我有一个包含两个包的程序.其中一个(CommonBundle)调度一个事件"common.add_channel",而另一个服务(FetcherBundle)应该调用它.在探查器上,我可以在"未调用的监听器"部分中看到事件common.add_channel.我不明白为什么symfony没有注册我的听众.

这是我的行动,里面CommonBundle\Controller\ChannelController::createAction:

$dispatcher = new EventDispatcher();
$event = new AddChannelEvent($entity);        
$dispatcher->dispatch("common.add_channel", $event);
Run Code Online (Sandbox Code Playgroud)

这是我的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

这应该是我的听众(FetcherService.php):

<?php

namespace Naroga\Reader\FetcherBundle\Service;

class FetcherService {

    public function onAddChannel(AddChannelEvent $event) {
        die("It's here!");      
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我注册我的监听器(services.yml)的地方:

kernel.listener.add_channel:
    class: Naroga\Reader\FetcherBundle\Service\FetcherService
    tags:
        - { name: kernel.event_listener, event: common.add_channel, method: onAddChannel }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?为什么symfony在调度common.add_channel时没有调用事件监听器?

Wou*_*r J 14

新事件调度程序对另一个调度程序上设置的侦听器一无所知.

在您的控制器中,您需要访问该event_dispatcher服务.Framework Bundle的编译器传递将所有侦听器附加到此调度程序.要获取服务,请使用Controller#get()快捷方式:

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

class ChannelController extends Controller
{
    public function createAction()
    {
        $dispatcher = $this->get('event_dispatcher');
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)