简体   繁体   中英

Zend Framework 2 - Get Controller and Action name in Layout

i have tried to get controller name and action name in layout file. But could not. In ZF1, we have used Front Controller instance to get the controller and action name. I have surfed the websites a lot. But there is no solution. How can i get in ZF2?

Controllers and their view scripts are decoupled. In fact, there could be several controllers involved in a single request.

If you want the controller and action the request got dispatched to, you can inject them by hooking into the dispatch event and inject the controller and action name in the attached ViewModel.

One way of doing that is inside the Bootstrap Event which should be in the Module class.

public function onBootstrap(\Zend\EventManager\EventInterface $e)
{
    $app = $e->getApplication();
    $app->getEventManager()->attach(
        'dispatch',
        function($e) {
            $routeMatch = $e->getRouteMatch();
            $viewModel = $e->getViewModel();
            $viewModel->setVariable('controller', $routeMatch->getParam('controller'));
            $viewModel->setVariable('action', $routeMatch->getParam('action'));
        },
        -100
    );

I got the above answer to work but I had to use the sharedManager to pass on the view to the controller

    $app = $e->getApplication();
    $app->getEventManager()->getSharedManager()->attach(
        __NAMESPACE__,
        'dispatch',
        function($e) {
            $routeMatch = $e->getRouteMatch();
            $viewModel = $e->getViewModel();
            $viewModel->setVariable('controller', $routeMatch->getParam('controller'));
            $viewModel->setVariable('action', $routeMatch->getParam('action'));
            $controller = $e->getTarget();
            $controller->view = $viewModel;
        },
        100
    );

If I wanted to use the above answer as is I had to do

    $this->getEvent('dispatch')->getViewModel()

in the controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM