How to Create Controller and Route in Magento 2

How to Create Controller and Route in Magento 2 - Lokesh Pawar

In Magento 2, action methods serve as the bridge between your code and the frontend. When you execute code, it’s the action method that ensures the output is correctly displayed on the frontend. This fundamental concept underscores the importance of mastering controllers, routes and actions.

Understanding Controller, Route and Action:-

For Example, your URL appears as follows :-                                    
             [route_name] [controller] [action]
           [route_name] [controller] [action]

Routes:- Routes define the mapping between URLs and specific controller actions, enabling the platform to process user requests effectively, we define route ID and frontname in the routes.xml file.

Controller:- A controller is a PHP class that manages the logic for a specific page which is present in the Controller folder.

Action:- In an action, a controller class contains a execute() method that is responsible for processing a specific request and generating an output.

Creating a Custom Controller in Magento 2

If you don’t know how to create basic module in Magento 2 – Read this article

Create routes.xml at this path:


<?xml version="1.0" ?>
<config xmlns:xsi=""
    <router id="standard">
        <route frontName="extension" id="extension">
            <module name="Lokesh_Module"/>

Create Index.php at this path and make sure, the first word should be capitalized while creating controller



namespace Lokesh\Module\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Action;

class Index extends Action
    protected $resultPageFactory;

    public function __construct(Context $context, PageFactory $resultPageFactory)
        $this->resultPageFactory = $resultPageFactory;

    public function execute()
        echo("Hello from Controller");

Run Cache flush command : php bin/magento cache:flush

Now, type URL in the browser according to your instance after baseUrl module/index/index


How to Create Controller and Route in Magento 2

Thank you for reading my Article! Feel free to share your thoughts or ask any questions in the comments section below and spread the word by sharing. Your engagement is appreciated!

Leave a reply

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

Cookies Notice

Our website use cookies. If you continue to use this site we will assume that you are happy with this.