我正在尝试基于此处给出的示例 - http://symfony.com/doc/master/components/event_dispatcher/introduction.html设置一个简单的事件订阅。Symfony2事件订户不会调用侦听器
这里是我的事件存储:
namespace CookBook\InheritanceBundle\Event;
final class EventStore
{
const EVENT_SAMPLE = 'event.sample';
}
这里是我的事件订阅:
namespace CookBook\InheritanceBundle\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
class Subscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
var_dump('here');
return array(
'event.sample' => array(
array('sampleMethod1', 10),
array('sampleMethod2', 5)
));
}
public function sampleMethod1(Event $event)
{
var_dump('Method 1');
}
public function sampleMethod2(Event $event)
{
var_dump('Method 2');
}
}
下面是services.yml的配置:
kernel.subscriber.subscriber:
class: CookBook\InheritanceBundle\Event\Subscriber
tags:
- {name:kernel.event_subscriber}
这里就是我如何引发事件:
use Symfony\Component\EventDispatcher\EventDispatcher;
use CookBook\InheritanceBundle\Event\EventStore;
$dispatcher = new EventDispatcher();
$dispatcher->dispatch(EventStore::EVENT_SAMPLE);
预期输出:
string 'here' (length=4)
string 'Method 1' (length=8)
string 'Method 2' (length=8)
实际输出:
string 'here' (length=4)
出于某种原因,听者方法不会被调用。任何人都知道这段代码有什么问题?谢谢。
干杯,特里斯坦。我需要重温我在symfony中对依赖注入的理解。 – Prathap
我看到你或多或少只是复制粘贴我的答案[这里](http://stackoverflow.com/questions/17671825/how-to-take-advantage-of-kernel-terminate-inside-an-event-listener )到你自己的问题没有在这里引用它 - 请给原来的答复下次:)一些功劳:) – nifr
是的完全我没有联系,因为背景是不同的,对我来说,我已经在一个监听器,所以我很害怕它会混淆事情。但是你的回答完全适用于这个问题。 –