可以在特定執行點注入自定義代碼使用事件。事件可自定義代碼,當事件被觸發時該代碼被執行。例如,當一個新的用戶在網站上註冊,一個日誌記錄器(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 });
上一篇:
Yii GridView Widget
下一篇:
Yii創建事件