Yii - 事件



您可以使用事件在某些執行點注入自定義程式碼。您可以將自定義程式碼附加到事件,當事件觸發時,程式碼將被執行。例如,當新使用者在您的網站上註冊時,日誌記錄物件可能會觸發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
});
廣告