核心提示:使用Yii::app()-user-getId()时会返回用户名(如test),可我们为了使用方便可能更希望返回的是用户的id,所以有了下面的改写。1、修改 components/UserIdenti...
使用Yii::app()->user->getId()时会返回用户名(如test),可我们为了使用方便可能更希望返回的是用户的id,所以有了下面的改写。
1、修改 components/UserIdentity.php
该类在用户登录时使用。
1、UserIdentity.php 中给后面变量赋值
$this->_id = $user->user_id; (如$this->_id = 10925)
2、重写 getId()方法:
public function getId() { return $this->_id; }
3、具体如下
class UserIdentity extends CUserIdentity { public $user_id;//添加的属性 public function getId() {//覆盖CUserIdentity中getId()方法 return $this->user_id; } public function authenticate() { $user_model = User::model()-> find('username=:name',array(':name'=>$this->username)); if($user_model === NULL){ $this -> errorCode = self::ERROR_USERNAME_INVALID; return FALSE; }else if($user_model->password !== $this->password){ $this->errorCode= self::ERROR_PASSWORD_INVALID; return FALSE; }else{ $this->errorCode = self::ERROR_NONE; $this->user_id = $user_model->user_id;//将用户id赋值给属性public $user_id,其中$user_model->user_id的user_id是数据库表单项的名字,如果你的数据库user_id是userid则进行相应替换,其余同理 return true; } } }
4、在程序中使用 Yii::app()->user->id 获取你的用户ID。
2、原理
登录操作下:
LoginForm 中
Yii::app()->user->login($this->_identity,$duration)
会到 CWebUser:
public function login($identity,$duration=0) { $id=$identity->getId(); ........
getId()是CUserIdentity中的方法:
//...... public function getId() { return $this->username; } //......
我们需要在UserIdentity.php中将继承的getId()方法覆盖,调用我们自己定义的返回内容。