Yii - Events



You can use events to inject custom code at certain execution points. You can attach custom code to an event, and when the event is triggered, the code gets executed. For example, a logger object may trigger a userRegistered event when a new user registers on your web site. If a class needs to trigger events, you should extend it from the yii\base\Component class.

An event handler is a PHP callback. You can use the following callbacks −

  • A global PHP function specified as a string.

  • An anonymous function.

  • An array of a class name and a method as a string, for example, ['ClassName', 'methodName']

  • An array of an object and a method as a string, for example, [$obj, 'methodName']

Step 1 − To attach a handler to an event you should call the yii\base\Component::on() method.

$obj = new Obj;
// this handler is a global function
$obj->on(Obj::EVENT_HELLO, 'function_name');
// this handler is an object method
$obj->on(Obj::EVENT_HELLO, [$object, 'methodName']);
// this handler is a static class method
$obj->on(Obj::EVENT_HELLO, ['app\components\MyComponent', 'methodName']);
// this handler is an anonymous function

$obj->on(Obj::EVENT_HELLO, function ($event) {
   // event handling logic
});

You can attach one or more handlers to an event. The attached handlers are called in the order they were attached to the event.

Step 2 − To stop in the invocation of the handlers, you should set the yii\base\Event::$handled property to true.

$obj->on(Obj::EVENT_HELLO, function ($event) {
   $event->handled = true;
});

Step 3 − To insert the handler at the start of the queue, you may call yii\base\Component::on(), passing false for the fourth parameter.

$obj->on(Obj::EVENT_HELLO, function ($event) {
   // ...
}, $data, false);

Step 4 − To trigger an event, call the yii\base\Component::trigger() method.

namespace app\components;
use yii\base\Component;
use yii\base\Event;
class Obj extends Component {
   const EVENT_HELLO = 'hello';
   public function triggerEvent() {
      $this->trigger(self::EVENT_HELLO);
   }
}

Step 5 − To detach a handler from an event, you should call the yii\base\Component::off() method.

$obj = new Obj;
// this handler is a global function
$obj->off(Obj::EVENT_HELLO, 'function_name');
// this handler is an object method
$obj->off(Obj::EVENT_HELLO, [$object, 'methodName']);
// this handler is a static class method
$obj->off(Obj::EVENT_HELLO, ['app\components\MyComponent', 'methodName']);
// this handler is an anonymous function

$obj->off(Obj::EVENT_HELLO, function ($event) {
   // event handling logic
});
Advertisements