我有一个问题,因为我在Zf2的路由参数中包含lang。我的有效路线很好,它正在工作。但是当我给出一个错误的路由时,这个异常出现了,它没有被zf2:
捕获Fatal error: Uncaught exception 'Zend'View'Exception'RuntimeException' with message 'No RouteMatch instance provided'[path]'vendor'zendframework'zendframework'library'Zend'View'Helper'Url.php on line 64
这是一个代码示例,我怀疑在错误路由的情况下是无效的:
<ul class="dropdown-menu">
<li><a href="<?= $this->url($this->route, array('lang' => 'fr'));?>">
<span class="flag fr"></span> Français
</a></li>
<li><a href="<?=$this->url($this->route, array('lang' => 'en'));?>">
<span class="flag gb"></span> English
</a></li>
</ul>
这是有道理的,这->路由是不正确的,当一个错误的路径提供,我需要改变什么修复,请?
如果您看一下Zend'View'Helper'Url
helper的第62行,很明显,只有当您将NULL
作为$name
参数传入时才会引发异常。
// ...Zend'View'Helper'Url.php
if ($name === null) {
if ($this->routeMatch === null) {
throw new Exception'RuntimeException('No RouteMatch instance provided');
}
因此,您需要确保在使用之前正确设置$this->route
视图变量。
在您的AnyModule'Module.php中编写以下行
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$eventManager = $application->getEventManager();
/**
* Zf2 View Url helper bug fix
* The problem is Url helper always requires RouteMatch
* if you used null in route name or set reuse matches to true
* even in 404 error but 404 itself means that there is not any route match ;)
*/
$eventManager->attach(
'Zend'Mvc'MvcEvent::EVENT_DISPATCH_ERROR,
function ($e) {
$application = $e->getApplication();
$serviceLocator = $application->getServiceManager();
$match = $application->getMvcEvent()->getRouteMatch();
if (null === $match) {
$params = [
'__NAMESPACE__' => 'Application'Controller',
'controller' => 'Index',
'action' => 'not-found',
// Here you can add common params for your application routes
];
$routeMatch = new 'Zend'Mvc'Router'RouteMatch($params);
$routeMatch->setMatchedRouteName('home');
$application->getMvcEvent()->setRouteMatch(
$routeMatch
);
}
}
);
}