我有一个包含两个bundle的程序。其中之一(CommonBundle)分派一个"common"事件。add_channel",而另一个(FetcherBundle)上的服务应该正在监听它。在分析器上,我可以看到公共事件。add_channel中的"未调用的监听器"部分。我不明白为什么symfony没有注册我的听众。
这是我的动作,在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 }
我做错了什么?为什么symfony在分派common.add_channel时不调用事件侦听器?
新的事件调度程序不知道其他调度程序上设置的侦听器。
在控制器中,需要访问event_dispatcher
服务。框架包的编译器传递将所有侦听器附加到该分派器。要获取该服务,请使用Controller#get()
快捷方式:
// ...
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
class ChannelController extends Controller
{
public function createAction()
{
$dispatcher = $this->get('event_dispatcher');
// ...
}
}