1. 程式人生 > >Yii2使用者資訊儲存與獲取

Yii2使用者資訊儲存與獲取

表單的資料是儲存在User模型裡,能實現登陸與退出功能. 這是動作方法

	public function actionLogin()
	{
	    $model=new User(['scenario'=>'login']);
	    if($model->load(Yii::$app->request->post())&&$model->login())
	    {
	        return $this->render('entry-confirm',['model'=>$model]);
	    }
	    else
	    {
	        return $this->render('login',['model'=>$model]);
	    }
	}

然後在User實現login方法

public function login()
{
    if(!$this->validate())
    {
        return false;
    }
    $user=Yii::$app->db->createCommand("select * from user where username=:username",[':username'=>$this->username])->queryOne();
    if($user!==null)
    {
        if($this->checkPassword($user['password']))
        {
            return Yii::$app->user->login(User::findOne(['username'=>$this->username]),$this->rememberMe ? 3600*24*7:0);
        }
        return false;
    }
    return false;
}

這裡還有個問題,如果這裡用 u s e r = U s e r :

: f i n g O n e ( [ u s e r n a m e = > user=User::fingOne(['username'=> this->username])獲取物件 。 然後用Yii:: a p p > u s e r > i d e n t i t y > u s e r n a m e v a r d u m p ( i i : : app->user->identity->username獲取資料,var_dump(ii:: app->user->identity):

app\models\User Object
(
    [username] => 
    [password] => 
    [rememberMe] => 
    [_attributes:yii\db\BaseActiveRecord:private] => Array
        (
            [id] => 6
            [username] => raohong
            [password] => $2y$13$4LMusps.IbhCfMBikgP6nuA.kmDmOyCqoKlbiOEv08lVhVZfiTbcy
            [authkey] => -l_yYwqmHQPrrkmXSNR097TVV3s4r_VV
            [accecctoken] => 
            [email] => [email protected]
        )

    [_oldAttributes:yii\db\BaseActiveRecord:private] => Array
        (
            [id] => 6
            [username] => raohong
            [password] => $2y$13$4LMusps.IbhCfMBikgP6nuA.kmDmOyCqoKlbiOEv08lVhVZfiTbcy
            [authkey] => -l_yYwqmHQPrrkmXSNR097TVV3s4r_VV
            [accecctoken] => 
            [email] => [email protected]
        )

    [_related:yii\db\BaseActiveRecord:private] => Array
        (
        )

    [_errors:yii\base\Model:private] => 
    [_validators:yii\base\Model:private] => 
    [_scenario:yii\base\Model:private] => default
    [_events:yii\base\Component:private] => Array
        (
        )

    [_behaviors:yii\base\Component:private] => Array
        (
        )

)
``````