Architect Magento | Tech Blogger | Magento Trainer
Mohamed Abbas | Architect Magento | Tech Blogger | Magento Trainer
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.
Magento\Framework\App\FrontController
) is the entry point for requests, determining the appropriate route, controller, and action method.
http://example.com/route_name/controller/action
routes.xml
Controller
directoryexecute()
method that processes the requestroutes.xml
FileThis file defines the route name and links it to the module.
File: app/code/Abbas/HelloWorld/etc/frontend/routes.xml
In this example, we’ll create a controller Index
with an execute()
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.
Define the page layout and template block for the controller.
File: app/code/Abbas/HelloWorld/view/frontend/layout/helloworld_index_index.xml
This block class will handle data and business logic for your template.
File: app/code/Abbas/HelloWorld/Block/Index.php
This .phtml
template file defines what is displayed on the page.
File: app/code/Abbas/HelloWorld/view/frontend/templates/index.phtml
Welcome to Magento Controller
Clear the cache to make sure the new controller and other configurations are loaded.
bin/magento cache:flush
Visit the URL:
http://example.com/helloworld/index/index
Or use the shorter format:
http://example.com/helloworld
Technical Lead | Magento Architect