Skip to main content

事件机制

Yii 引入了名为 yii\base\Component 的基类以支持事件。 如果一个类需要触发事件就应该继承 yii\base\Component 或其子类。

事件触发

trigger

事件绑定

on

取消绑定

off

使用顺序

控制器使用on绑定触发器,

事件中设置事件触发器。

附加事件处理器(Attaching Event Handlers)

调用 yii\base\Component::on() 方法来附加处理器到事件上。如:

$foo = new Foo;

// 处理器是全局函数
$foo->on(Foo::EVENT_HELLO, 'function_name');

// 处理器是对象方法
$foo->on(Foo::EVENT_HELLO, [$object, 'methodName']);

// 处理器是静态类方法
$foo->on(Foo::EVENT_HELLO, ['app\components\Bar', 'methodName']);

// 处理器是匿名函数
$foo->on(Foo::EVENT_HELLO, function ($event) {
//事件处理逻辑
});

触发事件(Triggering Events)

事件通过调用 yii\base\Component::trigger() 方法触发,此方法须传递事件名, 还可以传递一个事件对象,用来传递参数到事件处理器。如:

namespace app\components;

use yii\base\Component;
use yii\base\Event;

class Foo extends Component
{
const EVENT_HELLO = 'hello';

public function bar()
{
$this->trigger(self::EVENT_HELLO);
}
}

以上代码当调用 bar() ,它将触发名为 hello 的事件。

二、触发器传递参数。

需要继承 yii\base\Event

class CEvent extends Event{
const AA = '-------';
public $msg = '';
public function asd()
{
echo '|||||||||||||||';
}
}
class Cat extends Component
{
public function jiao()
{
echo 'miao miao miao';
$aa = new CEvent();
$aa->msg = 'asdassdasdasdasdasd';
$this->trigger('hello',$aa);
}
}
------------------接收传递来的参数--------------------------------
class Dog
{
public function run($e)
{
var_dump($e->msg) ;
$e->asd();
echo 'pao pao pao';
}
}

类级别的事件绑定

要使用yii\base\Event的on方法

    public function actionLogin()
{
$cat = new Cat;
$cat2 = new Cat;
$dog = new Dog;
// $cat->on('hello',[$dog,'run']); //普通的绑定
Event::on( Cat::className(),'hello',[$dog,'run']); //类级别的绑定
$cat->jiao();
$cat2->jiao();
}

绑定触发器的时候还可以让第三个参数是匿名函数

Run方法里面定义的触发器

/**
* Runs the application.
* This is the main entrance of an application.
* @return int the exit status (0 means normal, non-zero values mean abnormal)
*/
public function run()
{
try {
$this->state = self::STATE_BEFORE_REQUEST;
$this->trigger(self::EVENT_BEFORE_REQUEST);

$this->state = self::STATE_HANDLING_REQUEST;
$response = $this->handleRequest($this->getRequest());

$this->state = self::STATE_AFTER_REQUEST;
$this->trigger(self::EVENT_AFTER_REQUEST);

$this->state = self::STATE_SENDING_RESPONSE;
$response->send();

$this->state = self::STATE_END;

return $response->exitStatus;
} catch (ExitException $e) {
$this->end($e->statusCode, isset($response) ? $response : null);
return $e->statusCode;
}
}