2015-12-04 132 views
1

yii2註冊後如何實現自動登錄?在yii1中,我們通過用戶標識實現了這一點,但現在我無法找到它。Yii2註冊後自動登錄

我的控制器

public function actionCreate() 
{ 
    $model = new User(); 

    if ($model->load(Yii::$app->request->post()) && $model->save()) { 
     Yii::$app->session->setFlash('success', 'Please Login with Email/Password!'); 

     return $this->redirect('../site/login'); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 

如果註冊成功,我想自動登錄,而不是去站點登錄。

回答

4
if ($model->load(Yii::$app->request->post()) && $model->save()) { 

    \Yii::$app->user->login($model); 

    return $this->redirect(['/site/index']); 

} 
+0

我din't使用這種方法,因爲它實際上是調用了'swichIdentity()'用於做登錄(和我不知道OP是否想用這個強制登錄來記錄日誌),我寧願使用'swichIdentity()'。但我認爲這是一個意見問題:P – Clyff

+0

確定您可以使用'switchIdentity'而不是'login',但我認爲'login'更易於理解 – JustSamter

+0

謝謝您的回答。 –

2

您可以使用switchIdentity()方法完成該操作。

例子:

if ($userModel->load(Yii::$app->request->post()) && $userModel->save()) { 
    Yii::$app->user->switchIdentity($userModel); // log in 
    // do your stuff 
} 
+0

謝謝Clyff.giving你的時間.... –