PHP yii无法使用useridentity组件登录


php yii unable to login using useridentity component

这是我的认证控制器

class AuthController  extends Controller
{
    public function actionLogin()
    {
        $model = new LoginForm;
        $post = Yii::app()->request->getPost('LoginForm');
        // If form is submitted
        if($post) {
            $identity = new UserIdentity($post['username'], $post['password']);
            if($identity->authenticate()) {  // loop enters but could not get id
                echo Yii::app()->user->id;
                echo Yii::app()->user->getId();
            } else {
                echo 'failed';
            }
            //exit;
        }
        $this->render('login', array('model' => $model));   
    }
}

这是我的UserIdentity.php

class UserIdentity extends CUserIdentity
{

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

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

在上面的代码中,我在获取用户id(即)Yii::app()->user->getId();时遇到问题,这没有返回任何东西,我做了上面的代码

您正在创建LoginForm实例$model,但您从未使用它实际登录。如果您使用的是标准的LoginForm模型,那么它就是与UserIdentity类交互的。应该是这样:

if($post) {
    $model->attributes = $_POST['LoginForm'];
    if ($model->validate() && $model->login()) {  // loop enters but could not get id
        echo Yii::app()->user->id;
        echo Yii::app()->user->getId();
    } else {
        echo 'failed';
    }
    //exit;
}

如果你看一下LoginForm的login()函数,你会看到它调用Yii::app()->user->login($this->_identity,$duration);,这实际上是设置Yii::app()->user的方法被跳过。