我正在嘗試基於此處給出的示例 - 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
是的完全我沒有聯繫,因爲背景是不同的,對我來說,我已經在一個監聽器,所以我很害怕它會混淆事情。但是你的回答完全適用於這個問題。 –