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

This little tutorial explains a way how you can retrieve more parameters from Yii::app()->user by adding a component that extends CWebUser and retrieves the user information from database table named User.

There is also another method of doing this that retrieves the variables from session or cookie instead:
How to add more information to Yii::app()->user (based on session or cookie)

Steps to follow:

  1. Make sure you have got a database User model.
  2. Create a component that extends CWebUser.
  3. Specify in the config.php what user class the application must use.

1. The User model should be a file like this, that you probably already have, anyway for who doesn't:

<?php

// this file must be stored in:
// protected/models/User.php

class User extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'User';
	}
}
?>

2. Then we create the WebUser component:

<?php

// this file must be stored in:
// protected/components/WebUser.php

class WebUser extends CWebUser {

  // Store model to not repeat query.
  private $_model;

  // Return first name.
  // access it by Yii::app()->user->first_name
  function getFirst_Name(){
    $user = $this->loadUser(Yii::app()->user->id);
    return $user->first_name;
  }

  // This is a function that checks the field 'role'
  // in the User model to be equal to 1, that means it's admin
  // access it by Yii::app()->user->isAdmin()
  function isAdmin(){
    $user = $this->loadUser(Yii::app()->user->id);
    return intval($user->role) == 1;
  }

  // Load user model.
  protected function loadUser($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null)
				$this->_model=User::model()->findByPk($id);
		}
		return $this->_model;
	}
}
?>

3. The last step, configure the application

// you must edit protected/config/main.php
// and find the application components part
// you should have other components defined there
// just add the user component or if you 
// already have it only add 'class' => 'WebUser',

// application components
'components'=>array(
	'user'=>array(
		'class' => 'WebUser',
		),
),

That's all now you can use the following commands:
Yii::app()->user->first_name - property that returns name
Yii::app()->user->isAdmin() - function that returns admin status
And now you can add all the functions you want to WebUser component.

27 0
38 followers
Viewed: 153 008 times
Version: 1.1
Category: Tutorials
Tags:
Written by: atrandafir
Last updated by: Yang He
Created on: Jan 10, 2010
Last updated: 12 years ago
Update Article

Revisions

View all history