Though this questions is quite old, figured it might be worth adding a configuration based override here as well using a factory registered with the HelperPluginManager
:
Inside the module.config.php
:
'view_helpers' => array(
'factories'=> array(
'url' => 'Application\View\Helper\UrlFactory',
)
),
And the view helper plugin factory itself:
<?php
namespace Application\View\Helper;
use Zend\Console\Console;
use Zend\Mvc\Router\RouteMatch;
use Zend\Mvc\Router\RouteStackInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Helper\Url as BaseUrlHelper;
use Zend\View\HelperPluginManager;
class UrlFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $helperPluginManager
* @return mixed
*/
public function createService(ServiceLocatorInterface $helperPluginManager)
{
/**
* @var $helperPluginManager HelperPluginManager
* @var $router RouteStackInterface
*/
$serviceLocator = $helperPluginManager->getServiceLocator();
$helper = new Url();
$router = Console::isConsole() ? 'HttpRouter' : 'Router';
$router = $serviceLocator->get($router);
$helper->setRouter($router);
$match = $serviceLocator->get('application')
->getMvcEvent()
->getRouteMatch()
;
if ($match instanceof RouteMatch) {
$helper->setRouteMatch($match);
}
return $helper;
}
}
The trick here really is that in this factory, one only receives the HelperPluginManager
service locator. To access other services, one needs to fetch the global service locator first (which is done by the use
ing the global service locator from outside the closure in all other solutions).