English 中文(简体)
Yii Tutorial

Yii Useful Resources

Selected Reading

Yii - Events
  • 时间:2024-11-03

Yii - Events


Previous Page Next Page  

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 yiiaseComponent 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 yiiaseComponent::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 handpng 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 yiiaseEvent::$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 yiiaseComponent::on(), passing false for the fourth parameter.

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

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

namespace appcomponents;
use yiiaseComponent;
use yiiaseEvent;
class Obj extends Component {
   const EVENT_HELLO =  hello ;
   pubpc function triggerEvent() {
      $this->trigger(self::EVENT_HELLO);
   }
}

Step 5 − To detach a handler from an event, you should call the yiiaseComponent::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 handpng logic
});
Advertisements