標籤:cWeb style color io 使用 ar for 資料 art
此教程解釋了:如何通過增加一個擴充自 CWebUser 並從名為 User 的資料表中檢索使用者資訊的組件,從 Yii::app()->user 檢索更多參數。
也有另外一個方法來完成這個任務,它從 session 或 cookie 中檢索變數:
How to add more information to Yii::app()->user (based on session or cookie)。
步驟如下:
1. 確保你已經有一個資料庫 User 模型。
2. 建立一個擴充自 CWebUser 的組件。
3. 在 config.php 中指定應用使用的使用者類。
1. User 模型應當如下:
<?php
// this file must be 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. 然後我們建立 WebUser 組件:
<?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. 最後一步,配置應用
<?php
// you must edit protected/config/config.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‘,
),
),
?>
現在你可以使用如下命令:
Yii::app()->user->first_name - 返回名字的屬性
Yii::app()->user->isAdmin() - 返回 admin 狀態的函數
現在你可以增加你想要的任何函數到 WebUser 組件。
通過擴充 CWebUser 增加資訊到 Yii::app()->user