How to create a module in Magento 2

How to create a module in Magento 2 | A step-by-step guide

Magento 2 is a popular e-commerce platform that provides a range of features and functionality to enhance the user experience. It’s an open-source platform, which means it’s possible to create custom modules to extend its functionality as per the needs of a business. In this article, we’ll show you how to create a custom module in Magento 2 from scratch.

Step 1: Preparation

Before you start creating a custom module, there are a few things you need to prepare.

  • Familiarize yourself with the Magento 2 module structure and the basic concepts of Magento 2 module development.
  • Install Magento 2 on your local machine or set up a development environment on a remote server.
  • Install a code editor like Visual studio code or Sublime text.

Step 2: Create a Module Folder

Create a folder for your module under the “app/code” directory in your Magento 2 installation. The folder should be named after your company (Vendor name) and the module (Module name). For example, if your company name is “WebbyTroops” and the module name is “HelloWorld“, the folder should be named “WebbyTroops/HelloWorld“.

Step 3: Create the module.xml file

The module.xml file is the declaration file for your module. It defines the module’s name, version, and dependencies. Create the file in the “etc” directory within your module folder. The file should contain the following code:

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

Step 4: Create the registration.php file

The registration.php file is used to register your module with Magento 2. Create the file in the module’s root directory. The file should contain the following code:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

\Magento\Framework\Component\ComponentRegistrar::MODULE,
    'WebbyTroops_HelloWorld',
    _DIR_
);

Step 5: Create the route file

Create a new file in the “etc” directory called “frontend/routes.xml“. This file is used to define the frontend routes for your module. The file should contain 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="WebbyTroops_HelloWorld"/>
		</route>
	</router>
</config>

Step 6: Create the controller

In this step, we’ll create a controller file for our module. The controller is responsible for handling requests and returning responses. Create a new folder called the “Controller” directory, and then create a new file called “Index/Index.php“. The file should contain the following code:

<?php

namespace WebbyTroops\HelloWorld\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\PageFactory;

class Index implements HttpGetActionInterface
{

    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param PageFactory $resultPageFactory
     */
    public function __construct(PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
    }

    /**
     * Execute view action
     *
     * @return ResultInterface
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}

Step 7: Create layout file

In this step, we’ll create a layout handle for a page. This file will be used to define what will be visible on this particular page. We can define Containers, Blocks, or View Models to show the data as per our needs. Create a new file will be under the view/frontend/layout directory with the name helloworld_index_index.xml. To add a new Block to show hello world text on this page we have to declare a new block in this XML as follows:

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	<body>
		<referenceContainer name="content">
			<block name="hello_world" class="WebbyTroops\HelloWorld\Block\Index" template="WebbyTroops_HelloWorld::index.phtml"/>
		</referenceContainer>
	</body>
</page>

Layout handle file name is created as {ROUTE_ID}_{CONTROLLER}_{ACTION}.xml

Step 8: Create the block and template view file

In this step, we’ll create a block and template view file for our module. They help display fixed information such as text, images, etc. as well as dynamic information from a widget originating through the database and the block file contains all the functional logic used in the view template and the content related to HTML and PHP. Let’s create the custom Block class by following this code:

File: app/code/WebbyTroops/HelloWorld/Block/Index.php

<?php

namespace WebbyTroops\HelloWorld\Block;

class Index extends \Magento\Framework\View\Element\Template
{

    /**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }
    
    public function getHelloWorld() {
        return "Hello World";
    }
}

In the view file contains the HTML code that is displayed to the user. Create a new file called “index.phtml” in the “view/frontend/templates” directory. The file should contain the following code:

<h1><?= $block->getHelloWorld() ?></h1>

Step 9: Enable the module

The final step is to enable the module. To do this, run the following command in the Magento 2 root directory:

php bin/magento module:enable WebbyTroops_HelloWorld
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento cache:flush

Conclusion

In this article, we’ve shown you how to create a custom module in Magento 2. By following these steps, you’ll be able to extend the functionality of your Magento 2 store and improve the user experience. If you have any questions or need additional help, please don’t hesitate to ask.

Go To Top