1

我有以下课程。但是当我尝试访问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;
    }

}
?>
4

1 回答 1

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',
    ),
...
),
于 2012-12-02T09:31:29.733 回答