本文介绍了Yii2 - 如何在用户身份中设置动态 authTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里,我扩展了Yii2的User
身份.
Here, I have extended User
Identity of Yii2.
这是我的配置.
'user' => [
'identityClass' => app\models\UserMaster::class,
'enableAutoLogin' => false,
'loginUrl' => ['/auth/login'],
'authTimeout' => 86400
],
这里,我静态定义了 authTimout
.但是,我想要做的是我想从数据库中获取超时值并将其设置在 authTimeout
中.
Here, I have defined authTimout
statically. But, What I want to do is that I want to fetch timeout value from database and set it in authTimeout
.
谢谢.
推荐答案
您可以在处理请求之前使用事件设置authTimeout
:
You can use event to set authTimeout
before request will be handled:
'as beforeRequest' => [
'class' => function (Event $event) {
/* @var $app \yii\web\Application */
$app = $event->sender;
$app->getUser()->authTimeout = (new Query())
->select('value')
->from('{{%settings}}')
->where('name = :name', ['name' => 'authTimeout'])
->scalar($app->getDb());
}
],
但可能更清晰的方法是创建自定义组件并在 init()
中处理它.
class WebUser extends \yii\web\User {
public function init() {
parent::init();
$this->authTimeout = (new Query())
->select('value')
->from('{{%settings}}')
->where('name = :name', ['name' => 'authTimeout'])
->scalar();
}
}
然后在您的配置中使用新组件:
Then use new component in your config:
'components' => [
'user' => [
'class' => WebUser::class,
'identityClass' => app\models\UserMaster::class,
'enableAutoLogin' => false,
'loginUrl' => ['/auth/login'],
],
// ...
],
这篇关于Yii2 - 如何在用户身份中设置动态 authTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!