Yii2中的 Class yii\web\User 是如果進行驗證登錄,如果我們使用User類驗證登錄會給我們減少很多麻煩。在此就拿Yii2中自帶的登錄功能進行說明。
配置。在應用配置文件components中添加user組件,默認是配置好了,不過可以自己配置的后台登錄功能。
'user' => [ 'identityClass' => 'app\models\User', // User這個模型必須要實現identity接口 'enableAutoLogin' => true, // 'loginUrl' => ['user/login'], // ... ]
在SiteController中可以查看登錄動作,如果是過直接pass掉,如果不是過客,再進行下一步,就new一個LoginForm對象
public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); //數據的導入, 調用模型登錄功能 if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } else { return $this->render('login', [ 'model' => $model, ]); } }
在公共模型文件中找到LoginForm模型
public function login() { //驗證規則 rules if ($this->validate()) { // 傳入第一User信息參數驗證登錄 這時配置文件User組件起作用了 通過yii\web\User驗證 return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); } else { return false; } }
這時可以進入到yii\web\User類中查看login動作是如何處理,不管如何處理,反正做了亂七八糟的一些事,最后返回一個布爾值。通過觸發事件來設置登錄信息。
//注意第一個參數是要IdentityInterface 得實例
public function login(IdentityInterface $identity, $duration = 0) { if ($this->beforeLogin($identity, false, $duration)) { $this->switchIdentity($identity, $duration); $id = $identity->getId(); $ip = Yii::$app->getRequest()->getUserIP(); if ($this->enableSession) { $log = "User '$id' logged in from $ip with duration $duration."; } else { $log = "User '$id' logged in from $ip. Session not enabled."; }
//寫入日志 Yii::info($log, __METHOD__); $this->afterLogin($identity, false, $duration); } return !$this->getIsGuest(); }