How Magento 2 Controllers Work
Creating a controller in Magento 2 involves setting up various files and configurations to handle incoming requests, process them, and render responses. Magento 2 controllers come in two types: frontend (for customer-facing operations) and backend (for admin operations). While they share a similar setup, backend controllers often include permission checks like form keys.
How Magento 2 Controllers Work
Controllers receive and process requests from users (e.g., web browsers). The FrontController (Magento\Framework\App\FrontController) is the entry point for requests, determining the appropriate route, controller, and action method.
Example URL:
http://example.com/route_name/controller/action
- route_name: Defined in
routes.xml - controller: Subfolder inside the
Controllerdirectory - action: Class with an
execute()method that processes the request
Steps to Create a Controller in Magento 2
Step 1: Create the
routes.xmlFileThis file defines the route name and links it to the module.
File:
app/code/Abbas/HelloWorld/etc/frontend/routes.xml
Step 2: Create the Controller File
In this example, we’ll create a controller
Indexwith anexecute()method to define the main functionality.File:
app/code/Abbas/HelloWorld/Controller/Index/Index.php
_pageFactory = $pageFactory;
parent::__construct($context);
}
public function execute()
{
return $this->_pageFactory->create();
}
}
This controller extends Magento\Framework\App\Action\Action and defines the execute() method, where you can add logic to process the request.
Step 3: Create the Layout XML File
Define the page layout and template block for the controller.
File:
app/code/Abbas/HelloWorld/view/frontend/layout/helloworld_index_index.xml
Step 4: Create the Block Class
This block class will handle data and business logic for your template.
File:
app/code/Abbas/HelloWorld/Block/Index.php
Step 5: Create the Template File
This
.phtmltemplate file defines what is displayed on the page.File:
app/code/Abbas/HelloWorld/view/frontend/templates/index.phtml
Welcome to Magento Controller
Step 6: Flush Magento Cache
Clear the cache to make sure the new controller and other configurations are loaded.
bin/magento cache:flush
Step 7: Test the Controller
Visit the URL:
http://example.com/helloworld/index/index
Or use the shorter format:
http://example.com/helloworld
Thanks for reading
Mohamed Abbas
Technical Lead | Magento Architect