0
votes

I'm trying to setup a view plugin to expose the route matches in Zend Framework 2. The plugin is something like this:

class GetRouteMatch extends AbstractHelper
{
    /**
    * Route match returned by the router.
    * 
    * @var RouteMatch.
    */
    protected $routeMatch;

    /**
    * Set route match returned by the router.
    * 
    * @param  RouteMatch $routeMatch
    * @return self
    */
    public function setRouteMatch(RouteMatch $RouteMatch)
    {
        $this->routeMatch = $RouteMatch;
        return $this;
    }

    public function __invoke($param)
    {
        return $this->routeMatch->getParam($param, false);
    }
}

What is the best way to setup the RouteMatch object? I have to do it in the module bootstrap or in the controller?

For the moment I've resolved this way inside the controller action

$renderer = $this->getLocator()->get('Zend\View\Renderer\PhpRenderer');
$routeMatch = $renderer->plugin('routeMatch');
$routeMatch->setRouteMatch($this->getEvent()->getRouteMatch());

The RouteMatch object is injected manually.. but I'm sure there's a better way

1
I think this is one of ellegant ways..Gabriel Santos

1 Answers

0
votes

The best is to initialize such code in your module class. You can attach an event there to inject dependencies like the routematch. However, the routematch will be available to inject soon. There is work in progress to set the routematch in a service locator. This means you can configure DI it will pull the routematch from the service locator. Then you don't need to write these things yourself anymore.