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

You are viewing revision #5 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.

next (#6) »

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:

class UserIdentity extends CUserIdentity
	* User's attributes
	* @var array
	public $user;

	public function authenticate()

		if ($user)
			if ($user->password === md5($user->salt.$this->password)) {

		return !$this->errorCode;

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

	public function setUser(CActiveRecord $user)

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')) {
			if (isset($user[$name])) {
				return $user[$name];

		return parent::__get($name);

	public function login($identity, $duration) {
		$this->setState('__userInfo', $identity->getUserinfo()->attributes);
		parent::login($identity, $duration);

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


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

5 0
Viewed: 46 181 times
Version: Unknown (update)
Category: Tutorials
Tags: rbac, user, Yii
Written by: emix
Last updated by: Anas AbuDayah
Created on: Aug 15, 2010
Last updated: 7 years ago
Update Article


View all history

Related Articles