Yii事件


可以在特定執行點注入自定義程式碼使用事件。事件可自定義程式碼,當事件被觸發時該程式碼被執行。例如,當一個新的使用者在網站上註冊,一個紀錄檔記錄器(logger)物件可能會引發 userRegistered 事件。
如果一個類需要觸發事件,則應該擴充套件 yii\base\Component 類。
事件處理程式是一個 PHP 回撥。您可以使用下面的回撥 -
  • 指定為字串的全域性PHP函式
  • 一個匿名函式
  • 一個類名的陣列和方法作為字串,例如, ['ClassName', 'methodName']

  • 一個物件的陣列和一個方法作為字串,例如 [$obj, 'methodName']

第1步 - 要將處理程式係結到一個事件,應該呼叫 yii\base\Component::on() 方法

$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
});
可以將一個或多個處理程式到附加事件。附加處理程式將會按它們在附連到該事件的順序來呼叫。
第2步 - 要停止在處理程式的呼叫,應該將 yii\base\Event::$handled 屬性設定為 true。
$obj->on(Obj::EVENT_HELLO, function ($event) {
   $event->handled = true;
});
第3步 - 要插入處理程式到佇列開始,可以呼叫 yii\base\Component::on() ,傳遞第四個引數的值為 false 。
$obj->on(Obj::EVENT_HELLO, function ($event) {
   // ...
}, $data, false);
第4步 - 觸發一個事件,呼叫 yii\base\Component::trigger() 方法。
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);
   }
}
第5步 - 要將事件附加一個處理程式,應該呼叫 yii\base\Component::off() 方法。
$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
});