2014-12-09 125 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); 
} 

记得返回重定向,否则操作仍将被执行。