通過擴充 CWebUser 增加資訊到 Yii::app()->user

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.