Controller

Controller is used to serve a request path. A request path look like this:

www.yourmagentoinstallation.com/frontname/section/action
  • frontname: Configured in the router.xml and must be unique.
  • section: Is a subfolder or folders to the action class.
  • action: An action class that will execute the reqeust.

This snippet will also create a layout.xml, Block and phtml for the action.

Use the Controller snippet in the Magento 2 module creator.

Files

view/frontend/templates/index/index.phtml

Hello index/index.phtml

view/frontend/layout/module_index_index.xml

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	<body>
		<referenceContainer name="content">
			<block class="Mage2Gen\Module\Block\Index\Index" name="index.index" template="Mage2Gen_Module::index/index.phtml"/>
		</referenceContainer>
	</body>
</page>

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="module" id="module">
			<module name="Mage2Gen_Module"/>
		</route>
	</router>
</config>

Controller/Index/Index.php

<?php


namespace Mage2Gen\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context  $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}

Block/Index/Index.php

<?php


namespace Mage2Gen\Module\Block\Index;

class Index extends \Magento\Framework\View\Element\Template
{

}