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 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式