stevecj 发表于 2013-2-7 02:00:20

通过扩展 CWebUser 增加信息到 Yii::app()->user

通过扩展 CWebUser 增加信息到 Yii::app()->user

此教程解释了:如何通过增加一个扩展自 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
{
    /**
   * 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. 然后我们创建 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 组件。
页: [1]
查看完整版本: 通过扩展 CWebUser 增加信息到 Yii::app()->user