duande8497 2015-06-20 10:28
浏览 35
已采纳

处理Yii2中的访客以防止不断检查

I'm wondering what is generally the recommended way to handle guests in Yii2.

Like, for example when you have a logged in user you can simply get their details via a call such as:

$user = Yii::$app->user->identity;

Then you can do stuff like the below, depending on what details you made available for them:

$user->username;
$user->email;

However, obviously when we have a guest Yii::$app->user->identity returns null.

In my situation I constantly need to check if the user is a guest or a logged in user and hence have to repeat code like this in various places:

if (Yii::$app->user->isGuest) {
    $username = Yii::t('general', 'Guest');
} else {
    $username = Yii::$app->user->identity->username;
}

...doing this all over the place is obviously not very maintainable, so I am wanting to come up with a solution where I can just reference the username without having to do the check - but obviously I will still do guest checks where needed for security purposes, but I'm trying to write maintainable code and as such want to come up with a solution for purposes where I just need information such as their username.

I am not sure if there is currently any recommended way to do this in Yii2, but I thought perhaps something like extending the yii\web\User class and doing something like the below:

public function getIdentity() {

    $identity = parent::getIdentity();

    if (empty($identity)) {
        $identity = new stdClass();
        $identity->username = Yii::t('general', 'Guest');
    }

    return $identity;

}

Is that an advisable way to achieve what I want or is there a better way?

  • 写回答

1条回答 默认 最新

  • double0201 2015-06-20 12:31
    关注

    Extending User is a good idea, but you'd better add there new method like getUsername() or getAttributes() returning identity/guest default data. Your way will destroy User's 'getIsGuest' method which is based on 'getIdentity' null/not null return. And I believe this method is essential and changing it's response could break a lot of other things in your app.

    UPDATE. You may set your extended User class in config->components->user->class:

    [
        'components' => [
            'user' => [
                'class' => 'my
    amespace\User'
            ]
        ]
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面