2012-11-09 160 views
2

我在我的module.php中有一個函數,在下面的函數開始加載之前調用它,它驗證用戶已登錄,但我需要它重定向到登錄頁面如果用戶沒有登錄,我可以使用「標題」,但我想學習「Zend」做事的方式。Zend Framework 2,模塊重定向

public function preDispatch($e) 
{ 
    if (!isset($_SESSION)) session_start(); 

    $sm = $e->getApplication()->getServiceManager(); 
    $adapters = $sm->get('dbAdapters'); 
    if (!isset($_SESSION['auth'])) $_SESSION['auth'] = new MyAuth($adapters[1]); 

    if ($_SESSION['auth']->IsValid()) 
    { 
     echo 'Valid<br />'; 
    } 
    else 
    { 
     $e->getControllerClass()->redirect()->toRoute('login-success'); 
     echo '!Valid<br />'; 
     //REDIRECT TO LOGIN PAGE HERE!!!!! 
    } 
} 

回答

8

這是專門你問什麼:

 //REDIRECT TO LOGIN PAGE HERE!!!!! 

     /** 
     * grab Controller instance from event and use the native redirect plugin 
     */ 
     $controller = $e->getTarget(); 
     $controller->plugin('redirect')->toUrl('/logout?' . $query); 

     /** 
     * optionally stop event propagation and return FALSE 
     */ 
     $e->stopPropagation(); 
     return FALSE; 

話雖這麼說,你可能需要使用原始會議上重新審議。例如(假設你已經配置了一個自定義authAdapter):

public function checkSession($e) 
{ 
    $controller = $e->getTarget(); // grab Controller instance from event 

    $app   = $e->getApplication(); 
    $locator  = $app->getServiceManager(); 
    if ($controller instanceof LogoutController) return; 
    $authService = $locator->get('ds_auth_service'); 
    $authAdapter = $locator->get('ds_auth_adapter'); 

    /* 
    * try to authenticate 
    */ 
    if (!$authService->hasIdentity()){ 
     $result = $authService->authenticate($authAdapter); 
     if ($authService->hasIdentity()) { 
      $this->getEventManager()->trigger('authenticate', $this, array('result' => $result)); 
     } 
    } 

    /* 
    * If we are not in an exempt controller and no valid identity, redirect 
    */ 
    $isExempt = $controller instanceof \Application\Controller\LogoutController; 
    if (!$isExempt && !$authService->hasIdentity()) { 
     $query = http_build_query($result->getMessages()); 
     $controller->plugin('redirect')->toUrl('/logout?' . $query); 
     $e->stopPropagation(); 
     return FALSE; 
    } 

    // User is logged in 
    return TRUE; 

} 
+1

我得到這個錯誤,我已經試過,包括沒有成功neccessary文件,調用未定義的方法的Zend \的mvc \應用::插件() – rossedlin

+0

哦,謝謝你回覆:) – rossedlin