<?php
//----------------------- handles ---------------------------------
// OLog app\models\OLog.php
class OLog {
static public function add($event){
echo "我记录了一条登陆记录";
}
}
// Admin app\models\Admin.php
class Admin {
static public function sendMail($event){
echo "我给管理员发了邮件";
}
}
// User app\models\User.php
class User {
static public function notifyFirend($event){
$userId = $event->userId;
echo "告诉了朋友们我登陆了";
}
}
//------------ definde event that extends Event --------------------
// event/UserLoginEvent.php
use yii\base\Event;
class UserLoginEvent extends Event {
public $userId = 0;
}
//-------------events binding handles and use ------------------
use app\events\UserLoginEvent;
class UserController extends Controller {
// 定义事件名字
const EVENT_USER_LOGIN = 'user_login';
public function __construct(){
// 绑定事件
$this->on(self::EVENT_USER_LOGIN,['app\models\OLog','add']);
$this->on(self::EVENT_USER_LOGIN,['app\models\Admin','sendMail']);
$this->on(self::EVENT_USER_LOGIN,['app\models\User','notifyFirend']);
}
public function actionIndex(){
// 这里有一些代码.....
Yii::$app->user->login($user);
// 使用,并且传参为$event,可以把相关参数传递给调用者
$event = new UserLoginEvent();
$event->userId = $user->id;
$this->trigger(self::EVENT_USER_LOGIN,$event);
}
}