yii2yii-events

How to know if the triggered events succeed or fail in Yii2


I trigger an event in Yii2 transaction, and I want to know if the event handler succeed to commit the transaction, or fail to rollback.

Is a global variable or class const the right way?

What I do now is throwing an error in the event handlers.


Solution

  • Usually you're using event object to store state of event. Create custom event:

    class MyEvent extends Event {
    
        public $isCommited = false;
    }
    

    Use it on trigger and check the result:

    $event = new MyEvent();
    $this->trigger('myEvent', $event);
    if ($event->isCommited) {
        // do something
    }
    

    In event handler you need to set this property:

    function ($event) {
        // do something
        $event->isCommited = true;
    }
    

    If you want to break event flow you may use $handled property instead of isCommited and custom event.