事件
//在类中定义一个事件,推荐使用类常量表示事件名
const EVENT_HELLO = 'hello';
事件通过调用 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);
}
}
事件处理器
事件处理器是一个PHP 回调函数,当它所附加到的事件被触发时它就会执行。调用 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) {
//事件处理逻辑
});
可以附加一个或多个处理器到一个事件。当事件被触发,已附加的处理器将按附加次序依次调用。