Yii – Events


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 yiibaseComponent 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 yiibaseComponent::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, [''appcomponentsMyComponent'', ''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 yiibaseEvent::$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 yiibaseComponent::on(), passing false for the fourth parameter.

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

Step 4 − To trigger an event, call the yiibaseComponent::trigger() method.

namespace appcomponents;
use yiibaseComponent;
use yiibaseEvent;
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 yiibaseComponent::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, [''appcomponentsMyComponent'', ''methodName'']);
// this handler is an anonymous function

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

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *