我有一个问题因为我在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>
这是有道理的,当提供错误的路径时,这个&gt;路线是不正确的,我需要改变什么才能解决这个问题?
答案 0 :(得分:1)
在 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
);
}
}
);
}
答案 1 :(得分:0)
如果您查看line 62 of the Zend\View\Helper\Url
helper,则只有在NULL
参数传递$name
时才会引发异常。
// ...Zend\View\Helper\Url.php
if ($name === null) {
if ($this->routeMatch === null) {
throw new Exception\RuntimeException('No RouteMatch instance provided');
}
因此,您需要确保在使用之前正确设置$this->route
视图变量。