Yii2 事件--自定义事件和系统事件

本文详细介绍了在Yii2框架中如何实现自定义事件和系统事件的处理。通过一个登录时记录日志的例子,展示了事件定义、触发和处理的过程。此外,还讨论了如何在事件中添加相关信息,并利用yii2自带的afterAction事件进行控制器级别的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
首先撇开yii,让我们来理解一下js的事件
以js的click事件为例--点击按钮时的弹出警告,首先要定义click事件,然后在点击的时候回触发事件,最后是弹出警告。
事件就是这么一个过程。
总结一下,事件一共分为三个过程
1、定义事件
2、触发事件
3、处理事件
当然,我们在写代码完成的时候,要按照312来进行。
一、首先使用yii来看一下自定义事件。
这里就以写操作的时候写日志做为一个例子吧
1、处理事件--登录时记日志
在模型中
<?php
namespace frontend\models;
class WriteLog
{
public static function add(){
echo '记录日志成功';
}
}
2、在controller中定义事件
<?php
namespace 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中触发事件
<?php
namespace 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类
<?php
namespace frontend\events;
use yii\base\Event;
class CountryShowEvent extends Event
{
public $ip = 0;
}
在controller中定义添加event
<?php
namespace 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中修改
<?php
namespace 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值