问题描述
我编写了一个简单的url视图助手,它扩展了Zend\View\Helper\Url
并将其附加到ViewHelperManager
:
I wrote a simple url view helper, that extends Zend\View\Helper\Url
and attached it to the ViewHelperManager
:
MyNamespace\View\Helper\Url
MyNamespace\View\Helper\Url
namespace MyNamespace\View\Helper;
use Zend\View\Helper\Url as ZendUrl;
class Url extends ZendUrl {
public function __invoke($name = null, array $params = array(), $options = array(), $reuseMatchedParams = false) {
$link = parent::__invoke($name, $params, $options, $reuseMatchedParams);
...
return $link;
}
}
Application\Module
Application\Module
namespace Application;
use ...
class Module {
public function onBootstrap(MvcEvent $mvcEvent) {
$application = $mvcEvent->getApplication();
$serviceManager = $application->getServiceManager();
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$viewHelperManager->setInvokableClass('url', 'MyNamespace\View\Helper\Url');
...
}
}
现在,应用程序将引发异常:
Now the application throws an exception:
Zend \ View \ Exception \ RuntimeException:在第76行的/var/www/foo/bar/vendor/zendframework/zendframework/library/Zend/View/Helper/Url.php中没有提供RouteStackInterface实例
Zend\View\Exception\RuntimeException: No RouteStackInterface instance provided in /var/www/foo/bar/vendor/zendframework/zendframework/library/Zend/View/Helper/Url.php on line 76
我调试了两个Url
类.使用了Wenn MyNamespace\View\Helper\Url
,未调用方法Zend\View\Helper\Url#setRouter(...)
,并且未设置路由器.不知道为什么...
I debugged both Url
classes. Wenn MyNamespace\View\Helper\Url
is used, the method Zend\View\Helper\Url#setRouter(...)
is not called and the router is not set. Don't get why...
如何使其正常工作?
推荐答案
未经测试,所以我不知道它是否有效,我只是在猜测:
Not tested this so I don't know if it works, I am just guessing:
替换:
$viewHelperManager->setInvokableClass('url', 'MyNamespace\View\Helper\Url');
具有:
$viewHelperManager->setFactory('url', function ($sm) use($serviceLocator) {
$helper = new \MyNamespace\View\Helper\Url;
$router = Console::isConsole() ? 'HttpRouter' : 'Router';
$helper->setRouter($serviceLocator->get($router));
$match = $serviceLocator->get('application')
->getMvcEvent()
->getRouteMatch();
if ($match instanceof RouteMatch) {
$helper->setRouteMatch($match);
}
return $helper;
});
这篇关于在Zend Framework 2中扩展Zend \ View \ Helper \ Url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!