Add information to Yii::app()->user by extending CWebUser (better version)

You are viewing revision #7 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#6)next (#8) »

I found a better solution.

(Your login credentials may differ from my version so you will have to fit the script to your needs. I'm only telling what is the point)

Steps to follow:

  1. Add $user field to UserIdentity class
  2. Add getUser() method - getter for above property
  3. Add setUser($user) method - setter for above property which will assign user's properties info $user attribute.

My example UserIdentity class:

<?php
class UserIdentity extends CUserIdentity
{
	/**
	* User's attributes
	* @var array
	*/
	public $user;

	public function authenticate()
	{
		$this->errorCode=self::ERROR_PASSWORD_INVALID;
		$user=User::model()->findByAttributes(array('email'=>CHtml::encode($this->username)));

		if ($user)
		{
			if ($user->password === md5($user->salt.$this->password)) {
				$this->errorCode=self::ERROR_NONE;
				$this->setUser($user);
			}
		}

		unset($user);
		return !$this->errorCode;
	}

	public function getUser()
	{
		return $this->user;
	}

	public function setUser(CActiveRecord $user)
	{
		$this->user=$user->attributes;
	}
}
?>

Now user's attributes has been set, create WebUser class and place it under /protected/components

class WebUser extends CWebUser
{
	public function __get($name)
	{
		if ($this->hasState('__userInfo')) {
			$user=$this->getState('__userInfo',array());
			if (isset($user[$name])) {
				return $user[$name];
			}
		}

		return parent::__get($name);
	}

	public function login($identity, $duration) {
		$this->setState('__userInfo', $identity->getUser());
		parent::login($identity, $duration);
	}
}
?>

remember to set that class as Yii::app()->user class:

<?php
'components'=>array(
	'user'=>array(
		'class'=>'WebUser',
	)
)
?>

Should work now :) You can now access user's database fields as properties.