Yii2使用者資訊儲存與獲取
阿新 • • 發佈:2018-11-29
表單的資料是儲存在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; }
這裡還有個問題,如果這裡用 this->username])獲取物件 。 然後用Yii:: 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
(
)
)
``````