Create Magento 2 Module

Create Magento 2 Module
Facebooktwitterredditpinterestlinkedinmail

Create Magento 2 Module

Create a simple magento 2 module. From this article you will learn how to create a simple magento 2 module.

Amanweb\Common\etc\module.xml
Amanweb\Common\etc\frontend\routes.xml
Amanweb\Common\Controller\Index\Index.php
Amanweb\Common\Block\Common.php
Amanweb\Common\view\frontend\layout\common_index_index.xml
Amanweb\Common\view\frontend\templates\common.phtml

Step 1:
Create module file in the etc folders this file contains module version information.

Amanweb\Common\etc\module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Amanweb_Common" schema_version="1.0.0" setup_version="1.0.0"></module>
</config>

Step 2 :

Define front-end router that will create a front-end path for module.

Amanweb\Common\etc\frontend\routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="common" frontName="common">
            <module name="Amanweb_Common" />
        </route>
    </router>
</config>

Step 3 :

Create block :

Amanweb\Common\Block\Common.php

<?php
namespace Amanweb\Common\Block;
class Common extends \Magento\Framework\View\Element\Template
{
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
}

Step 4 :

Create controller

Amanweb\Common\Controller\Index\Index.php

<?php
namespace Amanweb\Common\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

Step 5 :

Create layout and view :

Layout
Amanweb\Common\view\frontend\layout\common_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <title>Welcome to Magento 2 World</title>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Amanweb\Common\Block\Common" name="common" template="common.phtml">
            </block>
        </referenceContainer>
    </body>
</page>

View
Amanweb\Common\view\frontend\templates\common.phtml

<strike> Magento 1</strike> Magento 2
<h1> Welcome to Magento 2 </h2>
<?php echo 'This is the Simple Welcome Module in Magento 2.0';?>

Note : Upload Amanweb module folder inside app/code/.

Add the module name inside the config file array.

'Amanweb_Common' => 1,

app/etc/config.php
Facebooktwitterredditpinterestlinkedinmail