Magento 2 Create Custom Module

Magento 2 comes with many default features and functionalities such as customer management, product management, category management, CMS pages, widgets, static blocks, reports, and more. Nowadays, customers and administrators often desire new functionalities and improvements to existing ones. Magento has a well-established structure for customizing existing functionalities and adding new ones through custom modules.

Today, we will learn how to create a custom module in Magento 2. Before we begin creating a custom module, let’s go over some important points regarding custom modules. Magento 2 modules are located in the ‘app/code’ or ‘vendor/’ folder. Modules can be installed using Composer, which places the module in the ‘vendor’ directory, or you can put the module’s ZIP file in the ‘app/code’ folder. We need to check the namespace of the module because it must be unique for each module, and it’s imported in each file within the module. Therefore, we advise using meaningful and concise names.

Let’s create a custom module for a better understanding. The ‘VendorName_Modulename‘ structure is used, where the ‘VendorName’ represents the main company name and ‘ModuleName’ signifies the specific function of the module in Magento 2. For instance, we’ll create a custom module named ‘Extendware_DemoModule‘.

Step-1: Begin by creating a folder inside the ‘app/code’ directory that corresponds to the structure of our module’s name.

Step-2: Create a ‘registration.php‘ file at ‘app/code/Extendware/DemoModule’ and add the following code.

Here, it’s crucial to ensure that you add the proper module name, which should match the folder name you’ve created within ‘app/code.

Step-3: Create a ‘module.xml‘ file at ‘app/code/Extendware/DemoModule/etc’ and add the following code.

The two files mentioned above are essential for registering your module within the Magento architecture, enabling you to interact with the system.

Step-4: create a ‘composer.json‘ file at ‘app/code/Extendware/DemoModule’ and add the following code.

Here, you must include the ‘type’ value as ‘magento2-module’. The file is particularly important when your module supports Composer installation. Nowadays, many modules are compatible with Composer installation, and Composer reads this information to install them into the Magento system.

After adding the above files, you need to run a Magento command to install the module into your Magento system. The command is as follows:

Once the above command runs successfully, you can find the module name listed below, and it will also appear in the main configuration file located at ‘app/etc/config.php.

Please note that when you install any module in Magento for the first time, it is enabled by default.

Have a question or need more information? Contact us, and we’ll be happy to help.
Follow us for daily inspiration and updates.