Categories: Yii框架教程

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
});
terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

6 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

2 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

3 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

4 周 ago