How to Create Controller in Magento 2
Step 1: Create routes.xml file.
File: app/code/Mageworld/HelloWorld/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="helloworld" id="helloworld"> <module name="Mageworld_HelloWorld"/> </route> </router> </config>
|
In the previous How to Create Module in Magento 2, we created file routes.xml. If you created it, you can ignore this step.
Step 2: Create controller file
File: app/code/Mageworld/HelloWorld/Controller/Index/Index.php
<?php
namespace Mageworld\HelloWorld\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);
} |
As you see, all controllers must be extended \Magento\Framework\App\Action\Action class which has dispatch method which 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.
Step 3: Create Layout file
File: app/code/Mageworld/HelloWorld/view/frontend/layout/helloworld_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="Magepworld\HelloWorld\Block\Index" name="helloworld_index_index" template="Mageworld_HelloWorld::index.phtml" /> </referenceContainer> </page> |
Step 4: Create a Block file
File: app/code/Mageworld/HelloWorld/Block/Index.php
<?php namespace Mageworld\HelloWorld\Block; class Index extends \Magento\Framework\View\Element\Template { } |
Step 5: Create a template file
File: app/code/Mageworld/HelloWorld/view/frontend/templates/index.phtml
<h2>My First Extension</h2> |
Step 6: Run a test
Let’s open the browser and navigate to
|