This tutorial explains how to retrieve more parameters from Yii::app ()->user by adding a component that extends from Cwebuser and retrieves user information from a data table named user.
There is also another way to accomplish this task, which retrieves variables from the session or cookie:
How to Add the information to Yii::app ()->user (based on session or cookie).
The steps are as follows:
1. Make sure you already have a database User model.
2. Create a component that extends from Cwebuser.
3. Specify the user class that the app uses in config.php.
1. The User model should read as follows:
<?php
//This file must is stored in:
//protected/models/user.php
class User extends Cactiverecord
{
Public static function model ($className =__class__)
{
return Parent::model ($className);
}
Public function TableName ()
{
return ' User ';
}
}
?>
2. Then we create the WebUser component:
<?php
//This file must is 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 was a function that checks the field ' role '
//In the User model to being equal to 1, that's 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. Last step, configure the application
<?php
//You must edit protected/config/config.php
//And find the application components part
//You should has other components defined there
//Just add the user component or if you
//already has it only add ' class ' = ' WebUser ',
//Application components
' components ' =>array (
' user ' =>array (
' class ' = ' WebUser ',
),
),
?>
Now you can use the following command:
Yii::app ()->user->first_name-Returns the property of the first name
Yii::app ()->user->isadmin ()-function to return to admin State
Now you can add any function you want to the WebUser component.
Add information to Yii::app ()->user by extending Cwebuser