>Dev Guide: How to Create Magento 2 Module in 5 Steps

Dev Guide: How to Create Magento 2 Module in 5 Steps

If you are a freelance Magento 2 developer or online merchants having a good demand of IT, the article today about “Step-by-step Tutorial on How to Create Magento 2 Module” is your must-read document. Why?

Magento 2 functionalities are out-of-box; however, online merchants always seek for the more efficient solutions to boost sales, improve the UX/UI, and enhance website performance. This reason lies at the heart of the increasing demand for Magento 2 extensions developments. Hence, if you are able to build Magento 2 modules that meet the requirements, you can earn lots of money. The further discussion about Magento 2 extension and why it should be used is available here.

Firstly, get started with what to prepare before creating Magento 2 module. 

Required Resources for Magento 2 Extensions Development

Truly speaking, Magento 2 is a sophisticated platform. Before you start creating an extension, please ensure a robust software architecture in advance.

1. Computer hardware

  • CPU: Debugging code uses a lot of resources from the CPU, so it is recommended to use the Intel 8th Gen Core i3.
  • Hard drive: 120Gb SSD is recommended to ensure the stability and data safety in the process, increase the durability, and speed up the code deployment of Magento 2 several times.
  • RAM: Though 8gb is enough, you should use 12 ~ 16 Gb. During the Magento 2 extensions developments, it needs to open multiple tabs and emulate BrowserStack, especially if using the IDE (Integrated Programming Environment).
  • Display: Full HD (1920×1080 pixels) is recommended. More than one screen is always better.

2. Software

This is an important factor that determines the quality of the generated Magento 2 extension.

  • Text Editor: PHPStorm IDE should be in use to manage the code source and to take advantage of the utility. For example, PHP_CodeSniffer is a real-time check functionality to test code during the Magento 2 module development process.
  • Composer: Built with PHP code, Magento 2 Composer is familiar with the programmer to manage the components used in the project. Install here.
  • Git: When creating Magento 2 extensions, developers use git to manage code, keep track of changes, fix bugs or update without interruption.
  • Xampp: a software to host PHP easily for beginners.
  • Magento 2 Platform: It is suggested to get the latest versions, check the default features, and find out which to improve with extensions.

5 Steps to Create Magento 2 Module with Detailed Example of Hello World Extension

To make the instruction easier to follow, we will give the example of how to build Magento 2 Hello World extension.

Step 1: Create the Hello World folder

In the root folder of Magento 2, create the code folder: /app/code/[Provider Name]/[Module Name] to stores all the source code.

Example: app/code/Bss/HelloWorld.

Step 2: Declare the module by module XML

At the following app/code/Bss/HelloWorld/etc/module.xml, in the module.xml file, insert the code as below.

<?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 module. Then, Magento will automatically recognize the registered module when scanning.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Bss_HelloWorld',
    __DIR__
);

In Magento root folder, open the Terminal window or Window PowerShell and type the command: php bin/magento setup: upgrade to test the result. how to create Magento 2 module

Step 3: Create a 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, create the Index.php controller file in the app/code/Bss/HelloWorld/Controller/Index/Index.php with the code as follow:

<?php

namespace Bss\HelloWorld\Controller\Index;

use Magento\Framework\App\Action\Context;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory;

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

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
     * |\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }
}

Step 4: Create a Block

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

Magento 2 use the MVC model (Model – View – Controller), in which block is used to store data. There are two basic steps to create block during Magento 2 extensions development.

Firstly, generate file in the app/code/Bss/HelloWorld/Block/HelloWorld.php and insert the code.

<?php
namespace Bss\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Helloworld constructor.
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Config\ScopeConfigInterface $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',    \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }
}

Then, create the data environment in the admin by creating file in the app/code/Bss/HelloWorld/etc/adminhtml/system.xml

<?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

In the app/code/Bss/HelloWorld/view/frontend/layout/helloworld_index_index.xml, create the layout file as follow:

<?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="Bss\HelloWorld\Block\HelloWorld" name="helloworld" template="helloworld.phtml" />
        </referenceContainer>
    </body>
</page>

Accordingly, create file in the app/code/Bss/HelloWorld/view/frontend/templates/helloworld.phtml with the following code.Here you see the created block is declared with a set template. This template is generated to display data of the next block.

<?php
/**
 * Product list template
 *
 * @var $block \Bss\HelloWorld\Block\Helloworld
 */
?>
<h1><?php echo $block->getHelloWorldTxt(); ?></h1>

$this variable is referencing our block class, so-called the method getHelloWorldTxt(). In the frontend, you should get the result like this:

how to create Magento 2 module

In the admin of this example, we will go to Store ⇒ Configuration ⇒ BSS Commerce ⇒ BSS Hello Word Setting. Here, there is data field declared in the system.xml.

how to create Magento 2 module

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

how to create Magento 2 module

Above is the 5-step instruction on how to create Magento 2 module with ease. However, have your work done? – Not yet!

Please scroll down and get the best practices to ensure the quality of your created module.

Pro tips to Create a Standardized Magento 2 Module

In this Magento 2 extension development tutorial, not only do we give you a brief instruction to build Magento 2 module from scratch but we also share the BSS Commerce module standardization guideline, with which we ensure that our Magento 2 extensions are well-coded and qualified for sale on Magento Marketplace. Feel free to refer.

Step 1: Get to Know Magento Coding Standard

When creating Magento 2 module, please keep PHP coding standard in mind if you want to publish your extensions and get paid. To automatically enforce these standards, Magento team recommends using PHP_CodeSniffer where possible or ensure that the extension has already been under a rigorous code review.

Step 2: PHP_CodeSniffer Installation

Get PHP_CodeSniffer and follow the attached guide to install it. On completing, please go to File ⇒ Setting. In the Popup, navigate your way through Language and Frameworks => PHP => Code Sniffer.

In Configuration, select Local and click on “…” then Open File in popup as follow.

how to create Magento 2 module

Find the path magento2\vendor\squizlabs\php_codesniffer\bin\phpcs.bat in the root folder of magento and select OK. To check, click the Validate button.

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

how to create Magento 2 module

Then, go to Editor=>Inspections => PHP => Quality tools => PHP Code Sniffer validation  và tick on enable box. In Coding Standard, select Custom sau đó click on “”.

how to create Magento 2 module

Here you see a popup be displayed, please open file. In Magento root folder, navigate to the following path: magento2\dev\tests\static\framework\Magento\ruleset.xml. Hit OK to have the path automatically filled in the popup.

how to create Magento 2 module

Eventually, tap Ok and turn off the Settings box. PHP_CodeSniffer is ready to check the code entered continuously. If there is something wrong with your code, messages will be.

Recommendations:

  • Always enable the CodeSniffer, even if the code is simple and easy to fix so that you can detect the errors quickly without wasting time to check the code later.
  • Setup Git as soon as you have created the code folder to create Magento 2 module. That way, you can keep track of the code development process, avoid loss meanwhile saving resources.

Here we give an example by checking the app/code/Bss/HelloWorld/Block/HelloWorld.php.

how to create Magento 2 module

Step 3: Prepare MEOP tools to check Magento 2 extension

EMEQP (Magento Marketplace Extension Quality Program) is a set of coding standards applied by Magento to ensure the quality specifications of Magento 2 extension before putting it on sales on the Magento Marketplace.

Today, we introduce you a helpful toolkit which supports the validation of MEQP violations during the Magento 2 module developments.

Installation

The tool will:

  • Check the Magento coding standard errors in the PHP files of the extension
  • Notify the type of errors and their places.
  • Advise to fix bugs
  • Important to note: The error with the severity = 8 and above is required to fix.

Terminal và command line

In the root folder of Magento, open the CMD/Window PowerShell by holding Shift + Right Click, then select Open Window PowerShell.

Command line:

vendor/bin/phpcs C:\xampp\htdocs\magento\magento2\magento2.2.x\magento2.2.5\app\code\Bss\HelloWorld –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 results:

how to create Magento 2 module

For example, let’s break down into the error with the severity=8.

how to create Magento 2 module

MEQP toolkit reports a bug at the 38th line in the \app\code\Bss\HelloWorld\Block\HelloWorld.php, along with a specific message: “The direct use of ObjectManager is discouraged, Inject necessary dependencies via constructor.”

It is essential to note that using Object Manager to call the functions directly will affect the quality of the extension as well as Magento 2 logic and software architecture. With such the common error, MEQP suggests using  Dependencies Injection on the __construct() function rather than use Object Manager directly.

how to create Magento 2 module

Wrapping up

In fact, how to create Magento 2 module often includes a large number of complex codes and logic in comparison with the Hello World module.  Hence, you should use MEQP tool as frequently as possible during the extension development.

We hope that the post is useful to save your precious time and effort while still ensuring the quality of the created Magento 2 extensions.