How to create simple module in magento 2
Let's name the module StackExchange_HelloWorld
.
you will need these files:
app/code/StackExchange/HelloWorld/registration.php
- the registration file
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'StackExchange_HelloWorld',
__DIR__
);
app/code/StackExchange/HelloWorld/etc/module.xml
- the module declaration file
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="StackExchange_HelloWorld" setup_version="2.0.0" />
</config>
app/code/StackExchange/HelloWorld/etc/frontend/routes.xml
- the frontend routing file
<?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="helloworld" frontName="helloworld">
<module name="StackExchange_HelloWorld" />
</route>
</router>
</config>
app/code/StackExchange/HelloWorld/Controller/Index/Index.php
- the index controller
<?php
namespace StackExchange\HelloWorld\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Index extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
public function __construct(
Context $context,
PageFactory $resultPageFactory
)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set(__('Hello World'));
return $resultPage;
}
}
app/code/StackExchange/HelloWorld/view/frontend/layout/helloworld_index_index.xml
- the layout file
<?xml version="1.0"?>
<page layout="2columns-left" 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="Magento\Framework\View\Element\Template" template="StackExchange_HelloWorld::index.phtml" />
</referenceContainer>
</body>
</page>
app/code/StackExchange/HelloWorld/view/frontend/templates/index.phtml
- the template for the block
<h2>Hello World</h2>
after you are done, run this in the console
php bin/magento setup:upgrade
You should be able to see the result at the url [ROOT]/helloworld
Well this is a broad question but my best advice would be to check the official Magento 2 samples.
You can find them here: https://github.com/magento/magento2-samples
This project is a collection of samples to demonstrate technologies introduced in Magento 2. You will find the most simple extension along with samples that incrementally add features to lead you through a exploration and education of the Magento 2 platform.
On top of that you can find many tutorials if you search "magento 2 create module" in Google