php - Yii2 - 如何在用户身份中设置动态 authTimeout?

标签 php yii yii2 yii2-advanced-app yii2-basic-app

在这里,我扩展了 Yii2 的 User 身份。

这是我的配置。

'user' => [
            'identityClass' => app\models\UserMaster::class,
            'enableAutoLogin' => false,
            'loginUrl' => ['/auth/login'],
            'authTimeout' => 86400
        ],

在这里,我静态定义了authTimout。但是,我想做的是从数据库中获取超时值并将其设置在 authTimeout 中。

谢谢。

最佳答案

您可以在处理请求之前使用事件设置authTimeout:

'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();
    }
}

然后在你的配置中使用新的组件:

'components' => [
    'user' => [
        'class' => WebUser::class,
        'identityClass' => app\models\UserMaster::class,
        'enableAutoLogin' => false,
        'loginUrl' => ['/auth/login'],
    ],
    // ...
],

关于php - Yii2 - 如何在用户身份中设置动态 authTimeout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52423705/

相关文章:

javascript - 为什么选择文件时此表单不自动提交?

PHP json_encode JSON_PRETTY_PRINT : how to print a different format?

php - 打开 Yii 应用程序导致下载 index.php

php - 在 Yii 中使用动态过滤器和动态连接执行搜索

PHP 日期比较

php - fatal error : Call to a member function prepare() on null in - Only in wordpress, 不在它之外

php - Yii2:编写表单 Action 的正确方式

class - yii2详细 View 条件行类

php - Ubuntu 16 yii1 数据库连接错误

yii2 - 如何在Yii2中的小部件内发布 Assets