Magento 2: Get Controller, Module, Action & Route Name

This article shows how we can get name of the current module, controller name, action name and route name in Magento 2.

Using Dependency Injection (DI)

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Framework\App\Request\Http class in the constructor of my module’s block class.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php


<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
	protected $_request;	
	
	public function __construct(
		\Magento\Backend\Block\Template\Context $context,
		\Magento\Framework\App\Request\Http $request,
		array $data = []
	)
	{		
		$this->_request = $request;
		parent::__construct($context, $data);
	}
	
	public function getControllerModule()
	{
		return $this->_request->getControllerModule();
	}
	
	public function getFullActionName()
	{
		return $this->_request->getFullActionName();
	}
	
	public function getRouteName()
	{
		return $this->_request->getRouteName();
	}
	
	public function getActionName()
	{
		return $this->_request->getActionName();
	}
	
	public function getControllerName()
	{
		return $this->_request->getControllerName();
	}
	
	public function getModuleName()
	{
		return $this->_request->getModuleName();
	}
}
?>

See more functions in vendor/magento/framework/App/Request/Http.php.

Now, we use can the function in our template (.phtml) file.


echo $block->getRouteName() . '<br />';
echo $block->getModuleName() . '<br />';
echo $block->getControllerName() . '<br />';
echo $block->getActionName() . '<br />';
echo $block->getFullActionName() . '<br />';
echo $block->getControllerModule() . '<br />';

Using Object Manager


$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();		

$request = $objectManager->get('\Magento\Framework\App\Request\Http');

echo $request->getRouteName() . '<br />';
echo $request->getModuleName() . '<br />';
echo $request->getControllerName() . '<br />';
echo $request->getActionName() . '<br />';
echo $request->getFullActionName() . '<br />';
echo $request->getControllerModule() . '<br />';

Hope this helps. Thanks.