2015-07-13 20 views
0
class TestController extends Controller { 
    function init() { 
     if(!(strtolower(yii::$app->requestedRoute) == "account/login" || empty(yii::$app->requestedRoute))) 
     { 
      if (false===$this->isLogin()) { 

       return $this->redirect('/login'); //it works, will redirect 

      } 
     } else { 
      if($this->isLogin()) { 
       return $this->redirect('/purchaser/manifest'); //not work, won't redirect 
       //echo $this->redirect('/purchaser/manifest'); //work 


      } 
     } 
    } 
} 

我重寫了控制器。當我嘗試過濾時,我發現這個問題。我很困惑,有什麼幫助?yii2在init中重定向是否工作?

回答

3

從Yii2文檔:

萬一動作不應運行,該請求應當的beforeAction碼內通過提供必要的輸出 或重定向該請求處理 。否則,響應將爲 爲空。

public function beforeAction($action) 
{ 
    if (!parent::beforeAction($action)) { 
     return false; 
    } 
    // your custom code here 
    //Eg 
    if(something){ 
     $this->redirect('/login'); 
     return false; //not run the action 
    } 

    return true; // continue to run action 
} 

Yii2不關心init()函數的返回值。應用程序仍將繼續運行。 約redirect()功能,它將不會工作,直到申請完成(beforeAction返回false或一個行動返回)。所以當你在init()函數中調用redirect()函數什麼都不會發生。
但是return $this->redirect('/login');它的工作原理。爲什麼?因爲在這種情況下,應用程序在運行後重定向。
你可以試試,甚至寫$this->redirect('/login');它仍然有效。

+0

謝謝你的回答,但我不得不使用「echo $ this-> redirect('/ purchaser/manifest')」。至少我知道原因。 –