How To Create Controller In Magento 2

Steps to create Controller in Magento 2

Create routes.xml file

Directory

app/code/VendorName/ModuleName/etc/frontend/routes.xml

Content For 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="modulename" id="modulename">
            <module name="VendorName_ModuleName"/>
        </route>
    </router>
</config>

Create Controller file

The controller must be extended \Magento\Framework\App\Action\Action class which has a dispatch method that will call execute() method in action class. In this execute() method, we will write all of our controller logic and will return a response for the request.  

Directory

app/code/VendorName/ModuleName/Controller/Index/Index.php

Content For Index.php

<?php
namespace VendorName\ModuleName\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 Layout file

Directory

app/code/VendorName/ModuleName/view/frontend/layout/modulename_index_index.xml

Content for modulename_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="VendorName\ModuleName\Block\Index" name="modulename_index_index" template="vendorName_ModuleName::index.phtml" />
    </referenceContainer>
</page>

 

Create Block file

Directory

app/code/VendorName/ModuleName/Block/Index.php

Content for Index.php

<?php
namespace VendorName\Modulename\Block;
class Index extends \Magento\Framework\View\Element\Template
{

}

Create template file 

Directory

app/code/VendorName/ModuleName/view/frontend/templates/index.phtml

Content for Index.phtml

<h2>Welcome to TheOnlineHelper</h2>

Flush or Clear the Magento Cache

Run this command to clean the cache

php bin/magento cache:clean

Run a Test

Open the browser and Navigate

http://<yourhost.com>/modulename/index/index

If you are looking for Magento services, visit Magento Web Agency.