Step by Step Guide – Magento 2 Module Development In 5 Steps

Create module Magento 2 is essential in customizing core functionality to your application requirements. Magento 2 modules are structural components that make up the code base of the entire system. If you are a freelance Magento 2 developer or an online seller with good IT needs, then you should refer to our article below. This tutorial teaches you how to define and register modules in your shop as well as how to organize the Magento 2 module directory.

What Is a Module in Magento 2?

According to merchants and extension developers, modules are the central unit of the Magento platform. The blocks, controllers, helpers, and models required to build a specific store feature are contained in this collection of folders. It is the Magento platform’s unit of customization. Magento modules may be developed to carry out a variety of tasks, from affecting the user experience to altering the look of the storefront. They might be added, taken away, or deactivated.

 5 steps to development Magento 2 modules with detailed example 

We’ll use the Magento 2 hello world module as an example of a Magento 2 module to make the instructions easier to understand.

Step1: create module Magento 2 Hello world folder

Create the code folder: /app/code/[Provider Name]/[Module Name] in the Magento 2 root folder to hold all the source code. Example, app/code/Bss/HelloWorld.

Step 2: use module XML to declare the module

Insert the following code in the module.xml: app/code/Bss/HelloWorld/etc.module.xml.

<?xml version="1.0"?>

<configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Bss_HelloWorld" setup_version="1.0.0">
    </module>
</config>

In app/code/Bss/HelloWorld/registration.php, please create the file by adding the code: Remember to register the created Magento 2 hello world module. When scanning, Magento will then detect the registered module automatically.

<?php
MagentoFrameworkComponentComponentRegistrar::register(
    MagentoFrameworkComponentComponentRegistrar::MODULE,
    'Bss_HelloWorld',
    __DIR__
);

Open the Terminal window or Window PowerShell and type the command: php bin/magento setup: upgrade to test the result, perform in the Magento root folder.

create module magento 2

Step 3: Create a Magento module controller

In the app/code/Bss/HelloWorld/etc/frontend/routes.xml, define the router using the following code.

<?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="Bss_HelloWorld" />
        </route>
    </router>
</config>

Next, in the app/code/Bss/HelloWorld/Controller/Index/Index.php create the Index.php controller file with the code as follow:

<?php

namespace BssHelloWorldControllerIndex;

use MagentoFrameworkAppActionContext;

class Index extends MagentoFrameworkAppActionAction
{
    /**
     * @var MagentoFrameworkViewResultPageFactory
     */
    protected $_resultPageFactory;

    /**
     * Index constructor.
     * @param Context $context
     * @param MagentoFrameworkViewResultPageFactory $resultPageFactory
     */
    public function __construct(Context $context, MagentoFrameworkViewResultPageFactory $resultPageFactory)
    {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * @return MagentoFrameworkAppResponseInterface|MagentoFrameworkControllerResultInterface
     * |MagentoFrameworkViewResultPage
     */
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }
}

Step 4: Create module Magento 2 block

As our example, the completed controller link will be like this: helloworld/index/index.

Magento 2 employs the Model-View-Controller (MVC) model, in which blocks are utilized to store data. When developing Magento 2 extensions, there are two fundamental phases to creating a Magento module block.

Make a file in the app/code/Bss/HelloWorld/Block/HelloWorld.php directory and paste the code.

<?php
namespace BssHelloWorldBlock;

class HelloWorld extends MagentoFrameworkViewElementTemplate
{
    /**
     * @var MagentoFrameworkAppConfigScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Helloworld constructor.
     * @param MagentoFrameworkViewElementTemplateContext $context
     * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
     */
    public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
    ) {
        parent::__construct(
            $context
        );
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @return mixed|string
     */
    public function getHelloWorldTxt()
    {
        $text = $this->getText();
        if (!isset($text)) {
            $text = 'Hello World';
        } else {
            $text = 'Hello '.$text;
        }
        return $text;
    }

    /**
     * @return mixed
     */
    public function getText()
    {
        return $this->scopeConfig
            ->getValue('helloworld/general/text_content',    MagentoStoreModelScopeInterface::SCOPE_STORE);
    }
}

Afterward, add a file in the app/code/Bss/HelloWorld/etc/adminhtml/system.xml directory to construct the data environment in the admin.
<?xml version=“1.0”?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="bss" translate="label" sortOrder="300">
            <label><![CDATA[Bss Commerce]]></label>
        </tab>
        <section id="helloworld" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>Bss Hello World Setting</label>
            <tab>bss</tab>
            <resource>Bss_HelloWorld::helloworld_config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <field id="text_content" translate="label comment" type="text" showInDefault="1" showInWebsite="1" showInStore="1" >
                    <label>Content goes here</label>
                </field>
            </group>
        </section>
    </system>
</config>

Step 5: Create layouts and templates

Create the layout file as follows in the location app/code/Bss/HelloWorld/view/frontend/layout/helloworld_index_index.xml.

<?xml version="1.0"?>

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" 
      layout="1column">
    <body>
        <referenceContainer name="content">
            <block class="BssHelloWorldBlockHelloWorld" name="helloworld" template="helloworld.phtml" />
        </referenceContainer>
    </body>
</page>

Accordingly, create the file in the app/code/Bss/HelloWorld/view/frontend/templates/helloworld.phtml with the following code. Here, you can see that the constructed block is specified using a pre-determined template. To show the data of the next block, this template is constructed.

<?php
/**
 * Product list template
 *
 * @var $block BssHelloWorldBlockHelloworld
 */
?>
<h1><?php echo $block->getHelloWorldTxt(); ?></h1>

This variable is referencing our block class, so-called the method getHelloWorldTxt(). You should get the result like this:

create module magento 2In the admin of this example, we will go to Store ⇒ Configuration ⇒ BSS Commerce ⇒ BSS Hello Word Setting. In the system.xml file, a data field is specified here.

create module magento 2

You can type new input, save and flush the Magento cache to get a similar result.

create module magento 2

Pro-tip to create module Magento 2 standardized development

In addition to providing you with a brief tutorial on how to create a Magento 2 module from scratch, we also share the BSS Commerce module standardization guideline in this tutorial on developing Magento 2 extensions. By following this guideline, we can make sure that our Magento 2 extensions are well-coded and suitable for sale on the Magento Marketplace. Do not hesitate to refer.

Step 1:  Get to know Magento coding standard

If you wish to publish your extensions and earn paid for them, please keep the PHP code standard in mind when developing Magento 2 modules. The Magento team advises utilizing PHP_CodeSniffer wherever feasible or making sure that the extension has already undergone a thorough code review in order to automatically enforce these standards.

Step 2: PHP_ Codesniffer installation

Get PHP_CodeSniffer and install it by using the instructions in the attachment. On completing, please go to File ⇒ Setting. In the Popup, navigate through Language and Frameworks => PHP => Code Sniffer.

Select Local under Configuration, then click “…” to open the file in a popup as seen below.

create module magento 2

Look in the root folder of Magento for the path magento2vendorsquizlabsphp_codesnifferbinphpcs.bat and select OK. To check, click the Validate button.

Note: as soon as PHPStorm is installed this PHP_CodeSniffer Validation setup should be done

create module magento 2

Then, go to Editor=>Inspections => PHP => Quality tools => PHP Code Sniffer validation and tick on enable box. In Coding Standard, select Custom and tick on“”.

create module magento 2

Here you see a popup displayed, please open the file. Navigate to the following location in the Magento root folder: magento2devtestsstaticframeworkMagentoruleset.xml. To have the popup’s path automatically filled in, click OK.

create module magento 2

At last, touch Ok to close the Settings window. PHP_CodeSniffer is prepared to continually review the input code. Messages will be displayed if your code is flawed.

Step3: Prepare MEOP tools to  check Magento 2 extension

Before placing a Magento 2 extension up for sale on the Magento Marketplace, Magento applies a set of coding criteria called the MMEQP (Magento Marketplace Extension Quality Program). Today, we’ll expose you to a practical toolbox that facilitates the validation of MEQP violations during the construction of Magento 2 modules.

Installation

The tool will:

  • Look for common Magento code problems in the extension’s PHP files.
  • Inform of the errors’ types and locations.
  • Advise fixing bugs
  • Important to note: The error with severity = 8 and above is required to fix.

Terminal and command line

In Magento root, hold Shift + Right Click to open CMD/Window PowerShell, then select Open Window PowerShell.

Command line:

vendor/bin/phpcs C:xampphtdocsmagentomagento2magento2.2.xmagento2.2.5appcodeBssHelloWorld –standard=MEQP2 –severity=8

In which, vendor/bin/phpcs is the command, C: … is the path to your extension code folder. Press enter to see the results:

create module magento 2

TO SUM UP

In contrast to the Hello World module, the Magento 2 module creation process frequently involves numerous sophisticated codes and logic. As a result, you should utilize the MEQP tool as much as feasible when developing the extension. We really hope that this post will help you save some of your valuable time and work while maintaining the caliber of the Magento 2 modules that were produced.

ONEXTDIGITAL is one of the world’s leading Magento extension providers and web development services. With experienced and certified Magento developers, we commit to bringing high-quality products and services to optimize our business effectively. Let us know about your problems. We are willing to support you every time.

>> Read more

Top 10 Best Magento 2 Websites For Your Inspiration In 2023