登陆后还要做另一些事情
- 本地留一个log
- 告诉登陆者的朋友它登陆了
- 发送一个邮件给管理员
// OLog app\models\OLog.php
class OLog {
static public function add($event){
$userId = $event->userId
echo "我记录了一条登陆记录";
}
}
// User app\models\User.php
class User {
static public function notifyFirend($event){
$userId = $event->userId;
echo "告诉了朋友们我登陆了";
}
}
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 = new UserLoginEvent();
$event->userId = $user->id;
$this->trigger(self::EVENT_USER_LOGIN,$event);
}
}
因为我知道Yii的 Component 类引入了Event事件,所有继承于Component的类都可以使用它,Controller继承了Component类。
我们可以通过
$this->on("事件名称","方法")