Trying to understand Yii::$app->user->identity->username

Hi,

I am not understand this, if someone could explain to me how it works:

‘label’ => ‘Logout (’ . Yii::$app->user->identity->username . ‘)’,

I first thought it would point to:

common\models\user and in a method called identity with a variable of "Username" but here I am confused, in the user.php file there is only this that refers to the word "Identity"




    public static function findIdentity($id)

    {

        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);

    }



There is absolutely nothing in that file that refers to the function "Identity", could someone explain this to me please? I cannot work out how yii2 can points to a single variable or function this way.

Thanks,

Ben

Yii::$app->user->identity is equivalent to Yii::$app->user->getIdentity(). It returns an IdentityInterface.

Check this doc here : http://www.yiiframework.com/doc-2.0/yii-web-user.html#getIdentity()-detail.

If you don’t find the method in the class file itself, you can try to look in the parent class (or in a Yii2 Behavior).

ciao

B)

Additional for understanding:

When you Look in your User Model you will see:




use yii\web\IdentityInterface; 


class User extends ActiveRecord implements IdentityInterface

{

... 

...

...

}




The namespace above has the file-path:

yourapp/vendor/yiisoft/yii2/web/IndentityInterface.php

You can open IdentitfyInterface and take a look at it.

Then you will get a better understanding.

Regards

Thank you so much for both your explanations, I got it:-)

Ben

Also, if a class implements another class all that means is that the class has to have ALL of the functions the other class has.

i.e.

class Users must have every function that Identity has or it is not a valid class. It’s a way for programmers to make sure other programmers are using all required functions for a class. Think of is as making a filed required on a form for a user. Same concept but for programmers writing classes.

So if you remove implements IdentityInterface your user class will still work but you could break other things if you remove any of those functions.