Hikmadh Commerce| Ecommerce Development Consulting | Magento Development and Consulting Service

How to Create a Module Development in Magento2

The architecture of the Magento system was designed to make the source code as modularized and extensible as possible. Customizing code usually means changing the behavior of the platform’s code. There’s a need for a Magento Module! In Magento 2, if you are following the best practices to update the source code, this is something you can reliably avoid most of the time.

 

Magento 2 module is the structural element that makes up the code base of the whole system. The module is essential in customizing core functionality according to your application requirements. This is useful when you have to add customized functionality.

 

In this article, you will learn how the Magento 2 module directory is structured and how to register and declare a module in your store.

What Is a Module in Magento 2?

 

According to merchants and extension developers, modules are the central unit of the Magento platform. It is a group of directories that contain the blocks, controllers, helpers, and models needed to create a specific store feature. It is the unit of customization in the Magento platform.

 

Magento modules can be created to perform multiple functions, from influencing user experience to changing storefront appearance. They can be installed, deleted, or disabled.

Structure for Creating a Module in Magento

 

To build a module in Magento 2, you need to understand the architecture of the module directory. Magento 2 architecture has two locations to create the module: app/code folder and the vendor folder.

In Magento 2, all the core modules located at vendor/magento/magento-* folders come under the installation of Magento 2. If you are building any overriding existing functionality or customizing the core module, the best practice is to select the app/code directory and commit the repository of the application.

 

Let’s take a quick overview of the source code folder structure to find where we need to place our code. To create a Magento 2 module, first, we need to set up the module’s structure by creating folders.

Step 1: Create the Magento 2 Module Directory

 

Let’s create the folder in the directory app/code to build the extension in a given structure defined as VendorName_ModuleName.We created Hikmadh_Mymodule, where the first part is the name of the vendor provider and the second part is the module’s name.

 

    • Hikmadh: namespace name.

 

    • Mymodule: module name.

 

    • Block: it’s a foundational building unit for layouts in Magento. It links a PHP block class (which contains logic) and a template (which renders content).

 

    • Model: for Models and ResourceModels

 

    • Observer: usually used when such an event is fired, the observer instantiates a Model to handle the necessary business logic for such an event.

 

    • Controller: controls the flow of application execution.

 

    • Helper: helper classes hold the code used in more than one application layer. For example, in the Cms module, helper classes are responsible for preparing HTML for presentation to the browser.

 

    • Setup: contains the migration and upgradation classes for schema and data creation of the database.

 

    • Index: controller name of the module and contains the action file.

 

    • etc: contains the configuration file of the module.

 

    • etc/Frontend: contains the router file.

 

    • view/Frontend: Contains Layout and Templates Folder.

 

    • view/Frontend/Layout: contain XML file.

 

    • view/Frontend/Templates: contain .phtml file.

 

    • Composer.json: used for the updating of product editions like the module. This file must be placed in the root directory of the module.

 

Below you’ll find the structure of the vendor/magento core module responsible for handling the Magento core functionality. Note that how Magento 2 module core code dependencies are inside the composer vendor folder.

 

Alright, now let’s do something more practical, shall we? Here’s the step-by-step tutorial to create the Magento 2 module.

Step 1: Create the Magento 2 Module Directory

 

Let’s create the folder in the directory app/code to build the extension in a given structure defined as VendorName_ModuleName.We created Hikmadh_Mymodule, where the first part is the name of the vendor provider and the second part is the module’s name.

 

app/code/Hikmadh/Mymodule

 

To use the command to create a folder:

  1. cd to the root folder
  2. mkdir app/code/Hikmadh
  3. mkdir app/code/Hikmadh/Mymodule

Step 2: Declare the Magento 2 Module

 

Declare the created Magento 2 module by using the configuration file. During the Magento 2 module development, the file system searches for the module’s configuration found in the, etc directory of the module. Create the configuration file module.xml.

 

This file contains information about the Module Name, Module Version, and dependencies of other modules. The code will look like this:

 
				
					<?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="Hikmadh_Mymodule" setup_version="1.0.0"> </module >
</config>
				
			

Let’s discuss the code a bit more to understand it better.

  1. <config>: Root node for configuration of Magento module.
  2. <module>: Basic information about the Magento module will be provided here.
  3. Name attribute in <module>: Namespace_Modulename the module name will be Hikamdh_Mymodule.
  4. Setup_version in <module>: This describes the current version of the database and data indicated by the module and tells Magento when to run the migration scripts. The version can help upgrade and install table schema.

 

Dependencies: If one module has some extended functionality depending on another Magento core module, the declaration is in the module.xml file. To mention the dependencies, use the following code:

				
					<module name="Hikmadh_Mymodule" setup_version="1.0.0">
<module name="Magento_Catalog"/> </sequence>
…..
</module>

				
			

Creating a module in Magento 2 is essential in declaring the dependencies of other modules in the module.xml file.

Step 3: Register the Created Module in Magento 2

The module has to be registered in the Magento 2 system using the Magento Component Registrar class that defines how to locate the module. Continuing our module, create the file registration.php in the module root directory:

 

The code will look like this:

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

This file calls the register method of ComponentRegistrar class with two parameters, the string Module tells the type we are going to register, and the other is our module name Hikmadh_Mymodule. This step holds important information in Magento 2 module creation.

 

  • Hikmadh: namespace name.
  • Mymodule:module name.

This standard file follows the same pattern for all modules; only the module name varies.

Step 4: Run the Command

The steps above should result in the creation of a simple module. To notify Magento of its presence, run the commands below:

				
					php bin/magento setup:upgrade
php bin/magento setup:di:compile
				
			

Step 5: Enable Magento 2 Module

Use the following command line to check if the module is enabled or disabled:

php bin/magento module:status

If you find your module in the disabled list, then you have to enable it by using the following command:

php bin/magento module:enable Hikamdh_Mymodule

You have enabled the module for the first time. Recheck the status and confirm the module is enabled. Also, you can open app/etc/config.php and check the file content for the Hikmadh_Mymodule key, whose value must be 1.

 

Create a Magento 2 Module Route

Now we’ll start implementing the route and controller to display some content in our created module. To define a route in the front-end, we need to create the file app/code/Hikmadh/Mymodule/etc/frontend/routes.xml with the following source 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 frontName="myroute" id="myroute">
            <module name="Hikmadh_Mymodule"/<
        </route>
    </router>
</config>
				
			

Let’s understand a bit more about the source code. In Magento 2, the structure of the URL contains three parts.

  1. frontName – route_id
  2. controller name – index
  3. action name – index

This will look like this:

 

http://hikmadh.com/index.php/frontname/controller/action

So, in our example, we are defining the route of the frontend area as defined in the routes.xml file. There are two attributes of the route tag: the Id and frontName. The ID should be unique to identify the router tag. Also, note it’s the best practice to keep the ID and frontName the same to avoid confusion.

Create a Controller and Action

Now we are telling Magento that our module will use the frontName defined in the routes.xml file. To create a Controller and action, make the folder in this path: app/code/Hikmadh/Mymodule/Controller/Index/Index.php.

 

Use the source code below to create the controller action:

				
					<?php


namespace  HIkmadh\Mymodule\Controller\Index;


use \Magento\Framework\App\Action\Action;

use \Magento\Framework\View\Result\PageFactory;

use \Magento\Framework\View\Result\Page;

use \Magento\Framework\App\Action\Context;

use \Magento\Framework\Exception\LocalizedException;


class Index extends Action

{




    /**

     * @var PageFactory

     */

    protected $resultPageFactory;




    /**

     * @param Context $context

     * @param PageFactory $resultPageFactory

     *

     * @codeCoverageIgnore

     * @SuppressWarnings(PHPMD.ExcessiveParameterList)

     */

    public function __construct(

        Context $context,

        PageFactory $resultPageFactory

    ) {

        parent::__construct(

            $context

        );

        $this->resultPageFactory = $resultPageFactory;

    }




    /**

     * Prints the statement

     * @return Page

     * @throws LocalizedException

     */

    public function execute()

    {

        echo "My module works";

        exit;

    }

}

				
			

After this, run php bin/magento cache:clean to check the result.


Your URL now should be:


http:///myroute/index/index


Example: https://magento-761105-2575467.hikmadh.com/myroute/index/index


Note: After finishing all steps, the output My module works should be displayed in your browser when you open the URL.