可以在特定执行点注入自定义代码使用事件。事件可自定义代码,当事件被触发时该代码被执行。例如,当一个新的用户在网站上注册,一个日志记录器(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创建事件