这是我的身份验证控制器
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();
这没有返回任何内容以及我做了上述代码的错误
答案 0 :(得分:0)
您正在创建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
,而您的方法被跳过了。