1

我有事件订阅者:

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

public function onEvent1()
{

}

public function onEvent2()
{

}

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

4

2 回答 2

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
        }
    }
}
于 2015-02-03T06:01:56.350 回答
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()
{

}

第一事件

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

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

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

第一个事件监听器

class FirstEventListener
{

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

        $event->setResult();
    }

}

它工作正常:)

于 2015-02-03T08:12:07.110 回答