UserIdentity和会话问题

时间:2012-12-01 21:59:27

标签: yii

我有以下课程。但是当我尝试访问Yii::app()->user->realName;时会产生错误。

我无法理解这一切。请帮忙!

以下代码是我UserIdentity类的代码。

<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    public $id, $dmail, $real_name;

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {
        $theUser = User::model()->findByAttributes(array(
                    'email' => $this->username,
                   // 'password' => $this->password
                ));
        if ($theUser == null) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        } else {
            $this->id = $theUser->id;
            $this->setState('uid', $this->id);
         //   echo $users->name; exit;
          //  $this->setState('userName', $theUser->name);
            $this->setState("realName",$theUser->fname .' '. $theUser->lname);
            $this->errorCode = self::ERROR_NONE;
        }
        return!$this->errorCode;
    }

}
?>

1 个答案:

答案 0 :(得分:3)

您需要扩展CWebUser类以获得所需的结果。

class WebUser extends CWebUser{
    protected $_realName = 'wu_default';

    public function getRealName(){
        $realName = Yii::app()->user->getState('realName');
        return (null!==$realName)?$realName:$this->_realName;
    }

    public function setRealName($value){
        Yii::app()->user->setState('realName', $value);
    }
}

然后,您可以使用realName分配和调用Yii::app()->user->realName属性。

protected $_realName是可选的,但允许您定义默认值。如果您选择不使用它,请将getRealName方法的返回行更改为return $realName

将上述课程放在components/WebUser.php中,或将其加载或自动加载的任何地方。

更改您的配置文件以使用新的WebUser类,您应该全部设置。

'components'=>
    'user'=>array(
        'class'=>'WebUser',
    ),
...
),
相关问题