Getting user model

Hello all!

I am working with yii2 and I have a question.

Why I can get the user properties on same way that others?

Examples:

I have a users table with this fields (id, name, email, password, auth_key, password_hash, password_reset_token, status, created_at, updated_at, role, avatar)

I want to get on any of my views, the avatar, this not works:


$model->avatar; 

Yii:$app->user->avatar;

This works:


$user->getAttribute("avatar");

Anyway, I have other models, and I can use it without problems using $model->propertie (with the $model received of the controller)

Its possible that users model (using advance template) works on a different way?

My userController index action have this:


public function actionIndex()

    {

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

        return $this->render('index',$model);

    }

You have to use




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



Because Yii::$app->user is a \yii\web\User instance, instead Yii:$app->user->identity is your User model class instance.

http://www.yiiframework.com/doc-2.0/yii-web-user.html

Yes, in most cases, but it’s better not to rely on that because it can be any object that implements yii\web\IdentityInterface and there are valid use cases for separating UserIdentity implementation from User model.

To make my code more future-proof I usually extend yii\web\User and add a getter for every attribute of user that needs to be available globally:




public function getModel()

{

  return $this->getIdentity();

}


public function getAvatar()

{

  return $this->model ? $this->model->avatar : null;

}



Now I can change the implementation of getModel() safely, without affecting any other parts of my application.

So if your model is dynamic, i think that you should check $this->model type in getAvatar() method, otherwise it could be not null but could be a type that has not "avatar" member.

Thanks! It works :)