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 snippet in the Magento 2 module creator.
Files
view/frontend/templates/index/index.phtml
Hello index/index.phtml
view/frontend/layout/mage2gen_module_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">
<body>
<referenceContainer name="content">
<block name="index.index" class="Mage2Gen\Module\Block\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 id="mage2gen_module" frontName="mage2gen_module">
<module name="Mage2Gen_Module"/>
</route>
</router>
</config>
Controller/Index/Index.php
<?php
declare(strict_types=1);
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
declare(strict_types=1);
namespace Mage2Gen\Module\Block\Index;
class Index extends \Magento\Framework\View\Element\Template
{
/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
}
}