简体   繁体   English

如何覆盖Yii2 $ app-> user-> identity

[英]How to Override Yii2 $app->user->identity

I have a module which uses a secondary database. 我有一个使用辅助数据库的模块。 In it, I am trying to log in to the user table from that secondary database. 在其中,我尝试从该辅助数据库登录到user表。 The problem is that the \\Yii::$app->user->identity->id is using the first database. 问题是\\Yii::$app->user->identity->id正在使用第一个数据库。 How should I override the class to do it like this? 我应该如何覆盖类来做到这一点? What I got in my LoginForm.php in the module is : 我在模块的LoginForm.php中得到的是:

public function login()
    {

        if ($this->validate() && $this->user) {
            $isLogged = Yii::$app->getUser()->login($this->user, $this->rememberMe ? $this->module->rememberFor : 0);
            //var_dump($this->user);exit;
            if ($isLogged) {
                $user = \frontend\modules\store\models\User::findOne(Yii::$app->user->identity->id);
                $user->last_login_at = time();
                $user->update();
              //  $this->user->updateAttributes(['last_login_at' => time()]);
            }

            return $isLogged;
        }

        return false;
    }

As you can see the user class here is overridden and it is using the secondary database. 如您所见,此处的user类已被覆盖,并且正在使用辅助数据库。 But how should I override the Yii::$app->user->identity->id to use this database also? 但是我该如何覆盖Yii::$app->user->identity->id来使用此数据库? Thank you in advance! 先感谢您!

You can override user identity in config 您可以在配置中覆盖用户身份

'user' => [
'identityClass' => 'app\models\User', // User must implement the IdentityInterface
'enableAutoLogin' => true,
// 'loginUrl' => ['user/login'],
// ...

] ]

more info here 更多信息在这里

As you are using Yii2 advanced template, you should consider adding a new sub application. 在使用Yii2高级模板时,应该考虑添加一个新的子应用程序。 Yii2 advanced template allows you to have different sessions for frontend and backend sub applications. Yii2先进的模板可以让你有不同会话frontendbackend副应用。 Advanced Template on Same Domain and different sessions 同一域和不同会话上的高级模板

Similarly, you can add a new app, in your case it may be called store . 同样,您可以添加一个新应用,在您的情况下,它可以称为store If you do it as a separate app, you can simply override identity class and even have different model for user . 如果您将其作为单独的应用程序进行操作,则可以简单地覆盖身份类,甚至可以为user使用不同的模型。 Help about adding new app is here. 有关添加新应用的帮助在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM