首先撇开yii,让我们来理解一下js的事件以js的click事件为例--点击按钮时的弹出警告,首先要定义click事件,然后在点击的时候回触发事件,最后是弹出警告。事件就是这么一个过程。总结一下,事件一共分为三个过程1、定义事件2、触发事件3、处理事件当然,我们在写代码完成的时候,要按照312来进行。一、首先使用yii来看一下自定义事件。这里就以写操作的时候写日志做为一个例子吧1、处理事件--登录时记日志在模型中<?phpnamespace frontend\models;class WriteLog{public static function add(){echo '记录日志成功';}}2、在controller中定义事件<?phpnamespace frontend\controllers;class CountryController extends Controller{const EVENT_COUNTRY_SHOW = 'country_show';public function __construct($id, Module $module, array $config = []){$this->on(self::EVENT_COUNTRY_SHOW,['frontend\models\WriteLog','add']);parent::__construct($id, $module, $config);}3、在country_show中触发事件<?phpnamespace frontend\controllers;class CountryController extends Controller{const EVENT_COUNTRY_SHOW = 'country_show';public function __construct($id, Module $module, array $config = []){$this->on(self::EVENT_COUNTRY_SHOW,['frontend\models\WriteLog','add']);parent::__construct($id, $module, $config);}public function actionShow(){$this->trigger(self::EVENT_COUNTRY_SHOW);}4、还可以在事件中添加相关信息我们可以看到trigger有两个参数,第二个参数是来传递相关event事件的,类型也是event创建event类<?phpnamespace frontend\events;use yii\base\Event;class CountryShowEvent extends Event{public $ip = 0;}在controller中定义添加event<?phpnamespace frontend\controllers;class CountryController extends Controller{const EVENT_COUNTRY_SHOW = 'country_show';public function __construct($id, Module $module, array $config = []){$this->on(self::EVENT_COUNTRY_SHOW,['frontend\models\WriteLog','add']);parent::__construct($id, $module, $config);}public function actionShow(){$event = new CountryShowEvent();$event->ip = \Yii::$app->request->getUserIP();$this->trigger(self::EVENT_COUNTRY_SHOW);}二、yii2自带的事件处理我测试的主要是在controller级的,应该会有多级控制在每个动作执行之后都会调用afterAction,这是触发事件其他都不变,主要是在controller中修改<?phpnamespace frontend\controllers;class CountryController extends Controller{public $layout = 'main1';const EVENT_COUNTRY_SHOW = 'country_show';public function __construct($id, $module, array $config = []){$this->on(self::EVENT_COUNTRY_SHOW,['frontend\models\WriteLog','add']);parent::__construct($id, $module, $config);}public function actionShow(){echo 'show test';}public function afterAction($action, $result){$event = new CountryShowEvent();$event->ip = \Yii::$app->request->getUserIP();$this->trigger(self::EVENT_COUNTRY_SHOW,$event);}
查看原文:http://www.architecy.com/archives/419
Yii2 事件--自定义事件和系统事件
最新推荐文章于 2020-12-09 14:41:45 发布