Handling Guests in Yii2 to prevent constant checks

1.2k views Asked by At

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

There are 1 answers

3
Pavel Bariev On BEST ANSWER

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\namespace\User'
        ]
    ]
]