Magento 2 – How to Get Controller, Module, Action, and Router Name

actioncontrollersmagento2modulerouter

Magento 2: How to get controller, module, action and router name?

Best Answer

Use the below code in the controller class to get the controller, module, action and route name:

<?php
    namespace Custom\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $request;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Request\Http $request
    ){
        parent::__construct($context);
        $this->request = $request;
    }

    public function execute()
    {
        $moduleName = $this->request->getModuleName();
        $controller = $this->request->getControllerName();
        $action     = $this->request->getActionName();
        $route      = $this->request->getRouteName();

        echo $moduleName."<br/>";
        echo $controller."<br/>";
        echo $action."<br/>";
        echo $route."<br/>";

        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }
}