Attila Szeremi
Attila Szeremi

Reputation: 5488

Get controller name from Module.php

I already managed to subscribe to the onDispatch() method in my Application\Module.php where more routing information should be available than onBootstrap().

public function onBootstrap(MvcEvent $e) {
    $em = $e->getApplication()->getEventManager(); 
    $em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'onDispatch'));
}

public function onDispatch(\Zend\Mvc\MvcEvent $e) {
    //$controllerName = /* ... ? */;
    $e->getViewModel()->setVariables(
        array('controllerName'=> $controllerName,
        'actionName' => $actionName)
    );
return parent::onDispatch($e);

What would I need to call to the the controller name? And I mean not the class, but say, if my controller class if Application\Controller\MyController, I would like to receive my-controller as what would be found in the URL. I also would not like to do string matching on the URL itself as I do not want to rely on it due to possible more complex routing.

Also, if you know, please tell me how I can also get the action name as well.

Upvotes: 0

Views: 3806

Answers (2)

Attila Szeremi
Attila Szeremi

Reputation: 5488

I finally found the answer. The answer is similar to what Bram Gerritsen said.

The thing is, the original controller parameter gets overridden by having the namespace prepended, capitalizing the controller name, dash separating what was camel case and such. This can be found in \Zend\Mvc\ModuleRouteListener near the end of the onRoute() method.

As can be seen, the original controller parameter gets saved under the __CONTROLLER__ parameter, or using constants \Zend\Mvc\ModuleRouteListener::ORIGINAL_CONTROLLER.

So in the end, if my current controller is \Application\Controller\MyControllerController and I wish to retrieve the original controller parameter (like my-controller, not Application\Controller\MyController), I need to call this:

public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
    $routeMatch = $e->getRouteMatch();
    $controllerParamName = \Zend\Mvc\ModuleRouteListener::ORIGINAL_CONTROLLER;
    $controller = $routeMatch->getParam($controllerParamName); // my-controller
}

Upvotes: 0

Bram Gerritsen
Bram Gerritsen

Reputation: 7238

You can get that information from the routematch which is available in the MvcEvent in the dispatch listener.

public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
    $routeMatch = $e->getRouteMatch();
    $controller = $routeMatch->getParam('controller');
    $action = $routeMatch->getParam('action');
}

Upvotes: 2

Related Questions