1
votes

I'm working on a service in ZF2 where i need to get the controller and action form an already build route. So is possible to somehow get the action and controller from the route?

Extended explanation:

I tried using

$controller = $this->params()->fromRoute('controller');
$action = $this->params()->fromRoute('action');

but what i need id fx i get a URL /accessadmin/addRole witch is the namespace\controller AccessAdmin\Controller\IndexController -> addRoleAction()

so i need a way to convert the route to AccessAdmin\Controller\IndexController and get the Action too.

Solved and result

<?php
use Zend\Http\Request;

class IndexController extends AbstractActionController {

    public function indexAction()
    {
        // Uri example.
        $uri = '/accessadmin/resources/addRole/4';

        $request = new Request();
        $request->setUri($uri);

        /** @var $router \Zend\Mvc\Router\Http\TreeRouteStack */
        $router = $this->getServiceLocator()->get('Router');

        $routeMatch = $router->match( $request );
        if($routeMatch !== null ) {
            $controller = $this->getServiceLocator()->get('Config')['controllers']['invokables'][$routeMatch->getParam('controller')];
            $action = $routeMatch->getParam('action');
        }
        // Lazy test
        var_dump($controller);
        var_dump($action);

        return new ViewModel();
    }

}

?>
1
Yes it is possible. Did you try?edigu
I am sorry i did not explain it properly, i tried several things but everything involves either changing my routes or some other hacked way. so I'm pretty lost now.KatsuoRyuu
So, if I understand correctly, you just got the URL and want to know what the controller and action would be if you dispatch it?ADi3ek

1 Answers

0
votes

If you're asking about getting these params from current route, then it's rather straightforward:

use Zend\Mvc\Controller\AbstractActionController;

class Index extends AbstractActionController {

    public function indexAction() {
        $controller = $this->params()->fromRoute('controller');
        $action = $this->params()->fromRoute('action');

        return new ViewModel();
    }
}

You may also want to know what the controller/action parameters would be for given URL string. In such case, you could just use the RouteMatch like this:

class Index extends AbstractActionController {

    public function indexAction() {

        $uri = '/accessadmin/addRole';

        $request = new Request();
        $request->setUri($uri);

        /** @var $router \Zend\Mvc\Router\Http\TreeRouteStack */
        $router = $this->getServiceLocator()->get('Router');

        $routeMatch = $router->match( $request );
        if($routeMatch !== null ) {
            $controller = $routeMatch->getParam('controller');
            $action = $routeMatch->getParam('action');
        }
    }
}