Search code examples
phpauthenticationyiiyii-components

How bind CWebUser with model User


How to bind Yii:app()->user to the model User. That there was a connection type: Yii::app()->user->getUser()

For example, I want to get the currently logged in user's email:

Yii::app()->user->getUser()->email;

I readed wiki post:http://www.yiiframework.com/wiki/80/add-information-to-yii-app-user-by-extending-cwebuser-better-version/


Solution

  • MyWbuser.php in components:

    class MyWebUser extends CWebUser{
    
        private $_profile = null;
        public $loginUrl='/';
    
        public function init(){
           parent::init();
           if(!$this->getIsGuest()){
                $this->_profile = User::model()->findByPk($this->getId());
           }
        }
        public function getProfile(){
           return $this->_profile;
       }
    }
    

    In config.php:

        'user' => array(
            'class' => 'MyWebUser',
        )
    

    Then you can use:

    Yii::app()->user->profile->name