Yii 中使用一个事件大概是这个样子的

// 绑定事件
$component->on($event::EVENT_NAME, [$object, 'methodNameA']);
$component->on($event::EVENT_NAME, [$object, 'methodNameB']);
// 触发事件
$component->trigger($event::EVENT_NAME, $event); 

源码

环境要求

  • Yii > 2.0

安装

$ composer require guanguans/yii-event -vvv

配置

...
'components' => [
    ...
    'event' => [
        'class' => \Guanguans\YiiEvent\Event::className(),
        'listen' => [
            // 事件类名
            \app\events\ExampleEvent::className() => [
                // 监听该事件监听的类名
                \app\listeners\ExampleListener::class,
            ],
        ],
    ],
    ...
],
...

使用示例

创建事件 app\events\ExampleEvent.php

namespace app\events;

use yii\base\Event;

class ExampleEvent extends Event
{
    public $name = 'example';
}

创建监听 app\listeners\ExampleListener.php

namespace app\listeners;

use Guanguans\YiiEvent\ListenerInterface;
use yii\base\Event;

class ExampleListener implements ListenerInterface
{
    public static function handle(Event $event)
    {
        // to do something.
        var_export($event->name);
    }
}

触发事件

Yii::$app->event->dispatch(new ExampleEvent());
// or
event(new ExampleEvent());

验证结果

'example'
03-05 23:36