通过扩展 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 组件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值