Accessing current users object

Hi all,

My starting point is the blog from the Yii blog tutorial, including the classes components/UserIdentity and models/User.

In order to authenticate a user, I try to find a match for username and password in the User table. This works fine and i can then store the users Id in the userIdentity.

The current users object is something I use at many different places of my websites, and therefore I’ll prefer to instantiate it only once. Normally i would do something like:




$user = User::findByPk(Yii::app()->user->id);



In which way do you prefer this, or which way is the most correct/best?

You could create your own user class:


class WebUser extends CWebUser {

    public function getCurrentUser() {

       return User::model()->findByPk($this->id);

    }

}



and configure it as ‘user’ component:


return array(

      'components' => array(

          'user' => array(

              'class' =>'WebUser'

          ),

  ...

Then Yii::app()->user->CurrentUser either is null (not found) or contains the according AR.

Okay, can you tell me when to use User::findByPk($this->id); and when to use the model() function?

Sorry, that was wrong, of course. Just fixed it. It always has to be User::model().

I suggest you use setState() method in components/UserIdentity.php .

The authenticate() method find the login user’s record and save the user id to Yii::app()->user->id property. You can use $this->setState(‘yourProperty’,$record->yourProperty) to save your current user attributes. And use Yii::app()->user->yourProperty to access it in other procedure.

setState() method