第一步:建立文件
<?php class UserIdentity extends CUserIdentity { /** * User's attributes * @var array */ public $user; public function authenticate() { $this->errorCode=self::ERROR_PASSWORD_INVALID; $user=User::model()->findByAttributes(array("email"=>CHtml::encode($this->username))); if ($user) { if ($user->password === md5($user->salt.$this->password)) { $this->errorCode=self::ERROR_NONE; $this->setUser($user); } } unset($user); return !$this->errorCode; } public function getUser() { return $this->user; } public function setUser(CActiveRecord $user) { $this->user=$user->attributes; } /** * 获取用户角色Id * @return string */ public function getRoleId() { $this_id=$this->getId (); $user = User::model ()->findByAttributes ( array ( 'mobile_phone' =>$this_id)); return $user === null ? '' : $user->role_id; } } ?>
第二步:现在用户的属性已经设置好了,创建WebUser类并把它放在/protected/components
<?php class WebUser extends CWebUser { public function __get($name) { if ($this->hasState('__userInfo')) { $user=$this->getState('__userInfo',array()); if (isset($user[$name])) { return $user[$name]; } } return parent::__get($name); } public function login($identity, $duration) { $this->setState('__userInfo', $identity->getUser()); parent::login($identity, $duration); } } ?>
第三步:记得在main.php配置中设置一下这个类Yii::app()->user
'components'=>array( 'user'=>array( 'class'=>'WebUser', ) )
使用如下代码调用
Yii::app()->user->getRoleId();