dst8922 2014-11-04 16:43
浏览 16
已采纳

类UserIdentity不返回Yii中的属性

i made this code with a tutorial:

class UserIdentity extends CUserIdentity
{
    private $_id;
    private $_email;

    public function authenticate()
    {
        $user=User::model()->findByAttributes(array('username'=>$this->username));
        if($user===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($user->password!==md5($this->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$user->id;
            $this->_email=$user->email;
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId()
    {
        return $this->_id;
    }
}

And i try to save that ID of the user, but it does not return the ID, it returns the emailadres, and the email is not defined when calling it like:

echo Yii::app()->user->email;

Please help me! Im new to Yii!

  • 写回答

1条回答 默认 最新

  • duanliang4009 2014-11-04 17:24
    关注

    You can override two methods of CUserIdentity:

    1. getName() //to get user name
    2. getId() //to get user id

    So you would have two properties by default:

    private $_name;
    private $_id;
    

    And you need to override mentioned methods:

    public function getId() {
        return $this->_id;
    }
    
    public function getName() {
        return $this->_name;
    }
    

    And

    $this->_id=$user->id;
    $this->name=$user->username;
    

    If you want to to save another user info such as email, you can use setState(), for example:

    $this->_id=$user->id;
    $this->name=$user->username;
    $this->setState('email', $user->email);
    

    Then use it in your project like below:

    Yii::app()->user->getState('email'); //will return stored email in session
    

    To get id , name you can use:

    $id=Yii::app()->user->id;
    $name=Yii::app()->user->name;
    

    In your case, it seems, yii is overriding name with email.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果