Magento 2 Development 02: Route Management and Controllers

0

 


In Magento 2 a standard url or a route contains three parts,

i) Front Name
ii) Controller Name
iii) Action Name

We need to register the front name with routes.xml file which will be under etc/frontend folder. Here frontend is a area code which refers to the front-end area. If we were creating route for admin then we have to adminhtml as area code.

<?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 id="blogmanager" frontName="blog">
<module name="Webkul_BlogManager" />
</route>
</router>
</config>

Here the route id is blogmanager and frontName is blog. Often for simplicity we use same value for route id and front name. Multiple modules can share the same route so we need to specify our module in the route tag.

Magento 2 area codes are,
i) frontend (Storefront)
ii) adminhtml (Magento Admin)
iii) base
iv) webapi_rest
v) webapi_soap
vi) graphql
vii) crontab

We need to create a folder with name Controller which will contain all controller related folders and files. Now we need create a folder with our controller name (eg. Manage) like Controller/Manage and under manage folder we need create the action file Add.php


<?php
namespace Webkul\BlogManager\Controller\Manage;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Add extends AbstractAccount
{
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
echo('<h1>Hello World</h1>');
}
}

The namespace should follow the directory structure and the class name will be filename.

Our action is extending Magento\Customer\Controller\AbstractAccount so this action can be accessed by logged in customer only. If an action extends Magento\Framework\App\Action\Action then that can be accessed by guest user also.

When we access the url, the execute function will be called. The url is given by frontName/controllerName/actionName which is blog/manage/add in our case.

2021-01-27_21-07

Note that since we are extending Magento\Customer\Controller\AbstractAccount class, we need to login first to access otherwise it will redirect to login page. If you face any error then run the di compile command to compile the code.

php bin/magento setup:di:compile

Folder structure till now,

2021-01-27_21-13

Post a Comment

0Comments
Post a Comment (0)
To Top