2013-08-28 48 views
9

我正在尝试基于此处给出的示例 - 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) 

出于某种原因,听者方法不会被调用。任何人都知道这段代码有什么问题?谢谢。

回答

7

您可以尝试注入配置EventDispatcher@event_dispatcher),而不是instanciating一个新的(new EventDispatcher

如果你只是创建它,并添加一个事件侦听器的Symfony仍然没有提及这个新创建的EventDispatcher对象并不会使用它。

如果你是一个控制器谁伸出ContainerAware内:

use Symfony\Component\EventDispatcher\EventDispatcher; 
use CookBook\InheritanceBundle\Event\EventStore; 

... 

$dispatcher = $this->getContainer()->get('event_dispatcher'); 
$dispatcher->dispatch(EventStore::EVENT_SAMPLE); 

我已经适应我的回答感谢this question's answer即使两个问题的背景是不同的,答案仍然适用。

+0

干杯,特里斯坦。我需要重温我在symfony中对依赖注入的理解。 – Prathap

+3

我看到你或多或少只是复制粘贴我的答案[这里](http://stackoverflow.com/questions/17671825/how-to-take-advantage-of-kernel-terminate-inside-an-event-listener )到你自己的问题没有在这里引用它 - 请给原来的答复下次:)一些功劳:) – nifr

+0

是的完全我没有联系,因为背景是不同的,对我来说,我已经在一个监听器,所以我很害怕它会混淆事情。但是你的回答完全适用于这个问题。 –

8

@Tristan说了些什么。服务文件中的标签部分是Symfony Bundle的一部分,并且只有在您将调度程序从容器中拉出时才会被处理。

你的榜样会按预期工作,如果你这样做:

$dispatcher = new EventDispatcher(); 
$dispatcher->addSubscriber(new Subscriber()); 
$dispatcher->dispatch(EventStore::EVENT_SAMPLE); 
+0

干杯,Cerad。我一直在寻找来自配置文件的注入,这正是特里斯坦所提出的。 – Prathap

+2

我完全理解。 @Tristan值得信任。这更多的是记录为什么它从容器中运行,而不是你的发布代码。 – Cerad

相关问题