Home  >  Article  >  Backend Development  >  YII2怎么自动更新上次登录时间

YII2怎么自动更新上次登录时间

PHPz
PHPzOriginal
2016-06-06 20:36:541603browse

YII2怎么自动更新上次登录时间

YII2怎么自动更新上次登录时间?

提出问题:

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

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

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加在这儿也没用。。。

解决办法:

首先明确两点
* 你的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
        }
    ],
    ...
]

更多相关技术知识,请访问PHP中文网

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn