使用事件订阅者

时间:2015-02-03 05:55:47

标签: symfony symfony-2.6

我有活动订阅者:

static public function getSubscribedEvents()
{
   return array(
      'event_1' => 'onEvent1',
      'event_2' => 'onEvent2',
   );
}

public function onEvent1()
{

}

public function onEvent2()
{

}

它正常工作,但我希望侦听器方法 onEvent1 仅在成功执行事件 event_1 后才能工作。我知道我可以优先考虑事件的方法,但它并没有解决我的问题。任何的想法?感谢。

2 个答案:

答案 0 :(得分:1)

您可以拥有保存操作状态的私有属性。在event_1中,如果操作成功,您可以更新标志,然后在event_2中检查标志是否处于您所需的状态:

class MyEventSubscriber{
    private $event1Successful = false;

    static public function getSubscribedEvents()
    {
       return array(
          'event_1' => 'onEvent1',
          'event_2' => 'onEvent2',
       );
    }

    public function onEvent1()
    {
        if(myOperation()){
            $this->event1Successful = true;
        }
    }

    public function onEvent2()
    {
        if($this->event1Successful){
            // your code here
        }
    }
}

答案 1 :(得分:0)

Broncha再次感谢您的回复。但我做的有点不同:

我的订阅者活动

static public function getSubscribedEvents()
{
   return array(
      'FirstEvent' => 'onMethod1',
      'SecondEvent' => 'onMethod2',
   );
}

public function onMethod1(FirstEvent $event)
{
    if ($event->getResult() == 'ready') {
         //code
    }
}

public function onMethod2()
{

}

FirstEvent

class FirstEvent extends Event
{
    private $result = 'no ready';

    public function setResult()
    {
        $this->result = 'ready';
    }

    public function getResult()
    {
        return $this->result;
    }
}

FirstEvent侦听器

class FirstEventListener
{

    public function onFirstEvent(FirstEvent $event)
    {   
        //code 

        $event->setResult();
    }

}

它工作正常:)

相关问题