Arman Mukatov
Arman Mukatov

Reputation: 140

Using Event Subscribers

I have event subscribers:

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

public function onEvent1()
{

}

public function onEvent2()
{

}

it works correctly but I want the listener method onEvent1 worked only after successfully execute event event_1. I know that i can put a priority for the method of the event, but it does not solve my problem. any idea? thanks.

Upvotes: 1

Views: 68

Answers (2)

Arman Mukatov
Arman Mukatov

Reputation: 140

Broncha thanks again for your reply. But I've done a little differently:

My subscriber events

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 Listener

class FirstEventListener
{

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

        $event->setResult();
    }

}

it works fine :)

Upvotes: 0

Broncha
Broncha

Reputation: 3794

You can have a private property saving the state of the operation. In event_1 if the operation is successful, you can update the flag, and then in event_2 check if the flag is in your required state:

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
        }
    }
}

Upvotes: 1

Related Questions