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

Magento has many numbers of modules, controllers, actions & routers, so it is little difficult to find the actual name of the module, controller, action or router name from the URL request. While we develop a Magento website, many times we need to get module, controller, action name from the current URL request. This post shows how we can get the name of the current module, controller, action, and route in Magento.

Use the below code in template files:

$this->getRequest() can be used in template (phtml) files.

Here is the code:

/**
 * get module name
 */
$this->getRequest()->getModuleName();
 
/**
 * get controller name
 */
$this->getRequest()->getControllerName();
 
/**
 * get action name, i.e. the function inside the controller
 */
$this->getRequest()->getActionName();
 
/**
 * get router name
 */
$this->getRequest()->getRouteName();

Use the below code in class files:

$this might not work in class (PHP) files. In this case, you need to use Mage::app().

Here is the code:

/**
 * get module name
 */
Mage::app()->getRequest()->getModuleName();
 
/**
 * get controller name
 */
Mage::app()->getRequest()->getControllerName();
 
/**
 * get action name, i.e. the function inside the controller
 */
Mage::app()->getRequest()->getActionName();
 
/**
 * get router name
 */
Mage::app()->getRequest()->getRouteName();

The above functions (getModuleName, getControllerName, getActionName, getRouteName) are present in the class Mage_Core_Model_Url.

You can explore all requests with print_r()

echo '<pre>';
    print_r(Mage::app()->getRequest());
echo '</pre>';

Hope this helps,

Leave a Reply

Your email address will not be published. Required fields are marked *