这里说的是通过行为的方式绑定事件
<?php
namespace api\components;
use Yii;
use yii\base\Behavior;
use yii\base\Application;
/**
* 事件类
*/
class EventService extends Behavior
{
// 定义事件名
const EVENT_BEFORE_DEMO1 = 'beforeDemo1';
/**
* [ 事件绑定处理程序 ]
* @return [type] [description]
*/
public function events()
{
return [
Application::EVENT_BEFORE_REQUEST => 'demo',
self::EVENT_BEFORE_DEMO1 => 'demo1',
];
}
/**
* [ 事件测试 ]
* @param [type] $event [description]
* @return [type] [description]
*/
public function demo($event)
{
Yii::info(['message'=>'事件测试(自动触发)'], 'demo');
}
/**
* [ 事件测试1 ]
* @param [type] $event [description]
* @return [type] [description]
*/
public function demo1($event)
{
$log = [
'message' => '事件测试1',
'ip' => $event->ip,
'route' => $event->route,
];
Yii::info($log, 'demo1');
}
}
<?php
namespace api\components;
use Yii;
use yii\base\Model;
use yii\base\Event;
/**
* ContactForm is the model behind the contact form.
*/
class MyEvent extends Event
{
/** @var [type] [ 请求路由 ] */
public $route;
/** @var [type] [ 请求IP ] */
public $ip;
}
在config/main.php中components同级定义
'name' => 'My Api',
'as behaviors' => 'api\components\EventService',
'components' => [ ... ]
/**
* [ 首页 ]
* @return [type] [description]
*/
public function actionIndex()
{
$event = new MyEvent();
// 传递参数
$event->ip = Yii::$app->request->userIP;
$event->route = Yii::$app->requestedRoute;
// 手动触发事件
Yii::$app->trigger(EventService::EVENT_BEFORE_DEMO1, $event);
}
2020-08-05 14:43:47 [127.0.0.1][-][-][info][demo] [
'message' => '事件测试(自动触发)',
]
in E:\data\www\project\php\yii2\advanced\api\components\EventService.php:35
2020-08-05 14:43:47 [127.0.0.1][-][-][info][demo1] [
'message' => '事件测试1',
'ip' => '127.0.0.1',
'route' => 'site/index',
]
in E:\data\www\project\php\yii2\advanced\api\components\EventService.php:50
in E:\data\www\project\php\yii2\advanced\api\controllers\SiteController.php:84
2020-08-05 14:43:47 [127.0.0.1][-][-][info][application] $_GET = []
Yii2 事件的使用就是这么简单,利用事件可以帮助我们完成很多功能。
const EVENT_BEFORE_REQUEST = 'beforeRequest',这个是yii\base\Application自带的事件,意思是"事件在应用程序开始处理请求之前引发的事件"。
有请求前的就肯定有请求后的事件。const EVENT_AFTER_REQUEST = 'afterRequest',意思是"事件在应用程序成功处理请求之后(在发出响应之前)引发的事件。"。
自定义的事件需要在特定需要的时候去触发。Yii::$app->trigger('定义事件名', 实例化event的类,可以传递参数,可以不传递)
以上就是对Yii2框架事件使用方法分享,各位大牛要是有更好的方法也请分享一下。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有