2013-08-28 8 views
9

ここに示した例に基づいて単純なイベントサブスクリプションを設定しようとしています - http://symfony.com/doc/master/components/event_dispatcher/introduction.html。ここでsymfony2イベントサブスクライバがリスナーを呼び出さない

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での設定です:

namespace CookBook\InheritanceBundle\Event; 

final class EventStore 
{ 
    const EVENT_SAMPLE = 'event.sample'; 
} 

はここに私のイベントサブスクライバです:

は、ここに私のイベント・ストアです

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はまだ、この新しく作成されたEventDispatcherたオブジェクトへの参照を持っていないイベントリスナーを追加する場合

答えて

7

あなたは代わりに新しいもの(new EventDispatcher

をinstanciatingで構成EventDispatcher@event_dispatcher)を注入しようとするかもしれませんそれを使用しません。

あなたが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。私は設定ファイルから注射を探していました。これはTristanが提示したものです。 – Prathap

+2

私は十分に理解しています。 @トリスタンは信用に値する。これは、あなたの投稿されたコードとは対照的に、なぜそれがコンテナから動作するのかを文書化するためのものでした。 – Cerad

関連する問題