Create Controller in Magento 2

Follow the below steps to create controller in Magento 2

Step 1: Create routes.xml file.
File: app/code/PHPCodez/First/etc/frontend/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="first" id="first">
  <module name="PHPCodez_First"/>
  </route>
  </router>
 </config>

Step 2: Create controller file
File: app/code/PHPCodez/First/Controller/Index/Index.php

<?php
 namespace PHPCodez\First\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();
  }
 }

Step 3: Create Layout file
File:app/code/PHPCodez/First/view/frontend/layout/first_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="PHPCodez\First\Block\Index" name="first_index_index" template="PHPCodez_First::index.phtml" />
  </referenceContainer>
 </page>

Step 4: Create Block file
File: app/code/PHPCodez/First/Block/Index.php

<?php
 namespace PHPCodez\First\Block;
 class Index extends \Magento\Framework\View\Element\Template
 {
 }

Step 5: Create template file
File: app/code/PHPCodez/First/view/frontend/templates/index.phtml

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

Step 6: Flush Magento cache
Run the following command from server

php bin/magento cache:flush

Leave a Reply

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