2014-12-09 117 views
0

以下是我面對的問題,看起來很像這個錯誤;ZF2在控制器中的路由和重定向功能

An error occurred 
An error occurred during execution; please try again later. 
Additional information: 
Zend\Mvc\Exception\DomainException 

File: .../vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/Url.php:63 

Message: 
Url plugin requires that controller event compose a router; none found 

我從來沒有面對這個問題,而我試圖從我的控制器重定向。假設我在我的控制器中實現了以下重定向功能,這會產生上述錯誤;

public function __construct() 
    { 
     # Get user identity 
     $auth = new AuthenticationService();   
     if ($auth->hasIdentity()) { 
     $this->identity = $auth->getIdentity(); 
     } else { 
     $this->redirect()->toRoute('admin/login'); 
     } 
    } 

路由確實存在,我可以達到site.com/admin/login/ ..登錄是admin的孩子這麼符號一定是好的。我想知道發生了什麼問題,以及如何解決這個問題,甚至在哪裏尋找它也是一個很好的起點。

謝謝!

回答

1

如果你看看錯誤,看起來你不能在控制器的構造過程中使用重定向插件。

Url plugin requires that controller event compose a router; none found 

可能最好把這個代碼放在onDispatch函數中。

public function onDispatch(MvcEvent $e) 
{ 
    # Get user identity 
    $auth = new AuthenticationService(); 
    if ($auth->hasIdentity()) { 
     $this->identity = $auth->getIdentity(); 
    } else { 
     return $this->redirect()->toRoute('admin/login'); 
    } 
    return parent::onDispatch($e); 
} 

記得返回重定向,否則操作仍將被執行。