magento-2-create-controller

Magento 2: How to Create Controller

In Magento 2, a Controller is a PHP class that is used to handle HTTP requests and determine how to respond to those requests. A Controller is responsible for processing user input, making calls to models (if needed), and preparing the response. In Magento 2, controllers are used to handling user requests and returning a response, typically by rendering a page or returning a JSON response. Controllers are defined in modules, and the URLs that trigger them are defined in the module’s routing configuration. The URL structure used to access a controller is base_url/frontName/controllerName/actionName, where frontName is defined in the module’s routing configuration and controllerName and actionName are defined in the controller class.

How does the controller work?

In Magento 2, a controller works as follows:

  • A user makes a request by accessing a URL in the browser.
  • Magento 2 matches the URL to a route defined in the module’s routing configuration.
  • The router determines the correct module, controller, and action to execute based on the URL and the routing configuration.
  • The system calls the controller to execute() method, extracting and passing any URL parameters to the execute() method.
  • The controller handles the request by invoking models and preparing data for the view.
  • The controller returns a response, which is typically either a page render or a JSON response. A template file in the module’s view directory generates the response, making data passed from the controller access to the template.
  • The response is sent back to the user’s browser and displayed.

This process happens every time a user makes a request, and the controller is responsible for processing the request and generating a response. This allows Magento 2 to handle requests and respond dynamically, based on the user’s input.

How to create a controller in Magento 2?

You need to follow the following steps:

  • Create routes.xml
  • Create Controller file
  • Create a controller layout file
  • Create a controller Block file
  • Create a controller template file
  • Clear Magento cache

To create the module in Magento 2, follow how to create a module in Magento 2.

Create routes.xml

Magento 2 relies on the routes.xml file to effectively handle URL processing within the system. Magento 2’s routes.xml file defines the routing for each module, determining which controller and action execute upon accessing a specific URL. The routes.xml file is typically located in the etc directory of a module and contains one or more <route> elements, each of which defines a specific route and maps it to a front name, a module, and a controller.

Directory

app/code/GDBlogger/DemoModule/etc/frontend/routes.xml

Code of routes.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="routename" id="routename">
            <module name="GDBlogger_DemoModule"/>
        </route>
    </router>
</config>

Create Controller file

Directory

app/code/GDBlogger/DemoModule/Controller/Index/Index.php

Code of Index.php

<?php
namespace GDBlogger\DemoModule\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
	protected $_pageFactory;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $pageFactory)
	{
		$this->_pageFactory = $pageFactory;
		return parent::__construct($context);
	}

	public function execute()
	{
		return $this->_pageFactory->create();
	}
}

Create a controller layout file

Directory

app/code/GDBlogger/DemoModule/view/frontend/layout/routename_index_index.xml

Code of routename_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="GDBlogger\DemoModule\Block\Index" name="routename_index_index" template="GDBlogger_DemoModule::index.phtml" />
    </referenceContainer>
</page>

Create Block file

Directory

app/code/GDBlogger/DemoModule/Block/Index.php

Code of Index.php

<?php

namespace GDBlogger\DemoModule\Block;

class Index extends \Magento\Framework\View\Element\Template

{

}

Create template file

Directory

app/code/GDBlogger/DemoModule/view/frontend/templates/index.phtml

Code of the index.phtml

<h2>Welcome to gdblogger.com</h2>

Clear Magento Cache

Run the following command to clear the Magento cache

php bin/magento clear:cache

Test Controller

To test controller is working, open your browser and navigate to the following Url:

http://yourhost.com/routename/index/index

OR

http://yourhost.com/routename/

I hope this guide will be helpful to you. Please do not hesitate to contact us through the comments section if you have any further questions.

Leave a comment

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