YII2怎么使用afterLogin和beforLogin自动更新上次登录时间?


发现 Yii2 afterLogin beforLogin 两个方法(事件),但是不知道怎么才能使用。

User模型 我已经写了如下代码:


 php


 public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'activated_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at'
                ],
            ]
        ];
    }

因为 ActiveRecord 里只有数据库增删改查的事件,把 yii\web\User::EVENT_AFTER_LOGIN 加在这儿也没用。。。

PHP框架 yii 框架 yii2 php

爱笑的有希 10 years ago

首先明确两点
* 你的User Model是继承自 ActiveRecord
* afterLogin 和 beforeLogin 是 yii\web\User 的两个事件

那么你把 yii\web\User 的两个事件挂载在 User Model 肯定不会去触发了。

那么就可以通过配置来解决,我们知道,配置是支持事件挂载的;
例如:


 'components' =>[
    ...
    'user' => [
        'identityClass' => 'common\models\User',
        'enableAutoLogin' => true,
        'on beforeLogin' => function($event) {
            $user = $event->identity; //这里的就是User Model的实例了
            $user->last_login_at = time();
            $user->save();
            ...
        },
        'on afterLogin' => function($event) {
            //the same
        }
    ],
    ...
]

坚强的土豆 answered 10 years ago

Your Answer