How to Create Controller Route in Magento 2.x (API)

Controller routes is a important factor for any Module Development in MVC Framework. It work like to receive request, process that and then rendering. In Magento there are 2 types of controllers, Frontend Controller & Admin Controller ( knows as Backend Controller). The behaviour of these two controller are quite similar instead of checking permission in Admin Controller using form-key.

Before moving forward, let’s know about the route path:

http://itechinsiders.com/route_name/controller_name/action_class

Here,

route_name (frontName):  route_name/frontName define in routes.xml ( i.e. vendorName/moduleName/etc/frontend/routes.xml) 

controller_name: it is nothing but folder name inside of Controller (i.e.  vendorName/moduleName/Controller/controller_name/ )

action_class:  nothing but a .php class having execute() method to process business logic inside the controller_name folder. ( i.e. vendorName/moduleName/Controller/controller_name/action_class.php )

Step 1: Create routes.xml file

Follow the path “app\code\Itech\Insiders\etc\frontend\routes.xml” and put the code as below. Let’s suppose my vendor name is ‘Itech’ and module name is ‘Insiders’ also the route name is ‘magento’ (see below code)

[php]

<?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="magento" id="magento">
<module name="Itech_Insiders">
</route>
</router>
</config>;

[/php]

Step 2: Create Controller file

Follow the path “app\code\Itech\Insiders\Controller\Index\Index.php”

[php]

<?php
namespace Itech\Insiders\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)
{
return parent::__construct($context);
}

public function execute()
{

$this->sayHello();

}

public function sayHello()

{

/*

Put Your Logic here

*/

}
}

[/php]

Step 3: Now clean your magento cache by using :

[code]bin/magento cache:clean [/code]

Step 4:  Let’s open the URL

http://www.< yourdomain >.com/magento/index

You will get result “Hello  User” on screen .

ThankYou 🙂

Related Post

Leave a Reply

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