zf2 – Get the route name in a custom view helper

Martin Zellerphp, zf2 4 Comments

========================
IMPORTANT UPDATE: this is a very old post – find a better way in my post “zf2/zf3 – get the route name in a custom view helper
========================

 

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:

<?php
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();
   die;
 }

 /**
 * 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 4

  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.

  2. Pingback: zf3 – get the route match in a custom view helper | Freelancer Martin Zeller - php java angularjs react fullstack

Leave a Reply

Your email address will not be published. Required fields are marked *

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