php - Handling Guests in Yii2 to prevent constant checks -
i'm wondering recommended way handle guests
in yii2
.
like, example when have logged in user can details via call such as:
$user = yii::$app->user->identity;
then can stuff below, depending on details made available them:
$user->username; $user->email;
however, when have guest
yii::$app->user->identity
returns null
.
in situation need check if user guest or logged in user , hence have repeat code in various places:
if (yii::$app->user->isguest) { $username = yii::t('general', 'guest'); } else { $username = yii::$app->user->identity->username; }
...doing on place not maintainable, wanting come solution can reference username without having check - still guest checks needed security purposes, i'm trying write maintainable code , such want come solution purposes need information such username.
i not sure if there recommended way in yii2
, thought perhaps extending yii\web\user
class , doing below:
public function getidentity() { $identity = parent::getidentity(); if (empty($identity)) { $identity = new stdclass(); $identity->username = yii::t('general', 'guest'); } return $identity; }
is advisable way achieve want or there better way?
extending user idea, you'd better add there new method getusername() or getattributes() returning identity/guest default data. way destroy user's 'getisguest' method based on 'getidentity' null/not null return. , believe method essential , changing it's response break lot of other things in app.
update. may set extended user class in config->components->user->class:
[ 'components' => [ 'user' => [ 'class' => 'my\namespace\user' ] ] ]
Comments
Post a Comment