Populating Yii::app()->user automatically


My users are authenticated using apache/ldap before they even hit my code.

I would like to have the user db record loaded without having to pull it for each page request.

Assuming Yii::app()->user is where this data should be, where do i check to see if it is populated?

I am also a little stumped on where to put the Yii::app()->user populating function…

If I have overlooked an earlier post that covers this please point it out.



Did you try to extend CWebUser and load desired data into session.

Sorry for the delay, priorities changed.

Thanks for your suggestion. I have extended the CWebUser class and now have the user data loading automatically. I am noticing that the query is executed on each page load. I would like to get the data into the session so the data is only pulled once per session. Suggestions?

Can you share your code for extending CWebUser?

You can simply cache the whole user model within your WebUser class. Then in your actual User AR clas, you delete the cache in afterSave/afterDelete methods. This way the cache should always represent fresh data. Of course you can also do it using session instead of cache.

@ frocco

Something like this:

class WebUser extends CWebUser


   private $_model;

   public function getModel()


      if ($this->_model === null)


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


      return $this->_model;



// Now you can access the model with Yii::app()->user->model

see http://www.yiiframework.com/doc/api/CWebUser#setState-detail on how to manage sessions

I used the code in the following cookbook articles:



Is this not what you are after: http://www.yiiframework.com/doc/cookbook/6/

Yes. I have the user record being placed into the session, but am noticing that the db is still hit for the data on every page request. I am trying to only hit the db for the user data if it is not in the session.