zf2 – Get the route name in a custom view helper

Martin Zeller php, zf2 3 Comments

Ever tried to get the route name in your custom view helper in a zf2 (zend framework 2.1) project?
I searched a lot – until I realized that I have to call getServiceLocator on my serviceLocator instance 😉
This is the solution:

namespace YouCompany\YourNameSpace;

use Zend\ServiceManager\ServiceLocatorInterface;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\View\Helper\AbstractHelper;

class YourViewHelper extends AbstractHelper implements ServiceLocatorAwareInterface {

private $serviceLocator;

 public function __invoke() {
   $routeMatch = $this->serviceLocator->getServiceLocator()->get('Application')->getMvcEvent()->getRouteMatch();
   echo $routeMatch->getMatchedRouteName();

 * Set service locator
 * @param ServiceLocatorInterface $serviceLocator
 public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
   $this->serviceLocator = $serviceLocator;

 * Get service locator
 * @return ServiceLocatorInterface
 public function getServiceLocator() {
   return $this->serviceLocator;

Comments 3

  1. A view helper should not pull data. They should be injected through the constructor or setter. It allows easier testing.
    So consider getting the current route from the view helper factory.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.