How to Create a Custom Module in Magento 2
To create a custom Magento 2 module from scratch, follow these steps. This guide will take you through the process of creating and enabling your own Magento 2 module.
Overview
Magento 2 lets developers add features without altering core files. Creating a custom module is a key part of Magento development. You should create a custom module when you want to add features, integrate third-party services, create admin functionality, or customize the frontend experience.
Module Structure
Create the following directories and files inside your Magento installation:
app/code/Vendor/Extensions/
├── registration.php
└── etc/
└── module.xml
Step 1: Create Module Directory
First, create the following directory:
Magento automatically scans the app/code directory and loads all custom modules placed inside it.
Step 2: Create registration.php
Create the following file:
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Vendor_Extensions',
__DIR__
);
This file tells Magento that you have created a custom module called Vendor_Extensions.
Step 3: Create module.xml
Create the following configuration file:
<?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="Vendor_Extensions"
setup_version="1.0.0"/>
</config>
This file defines the module name and version. Magento uses this information when installing or upgrading the module.
Step 4: Enable the Module
Run the following commands from your Magento root directory:
php bin/magento module:enable Vendor_Extensions
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush
These commands enable the module, update Magento's module list, generate dependency injection files, deploy static content, and clear the cache.
Step 5: Verify Module Status
To verify that the module is enabled successfully, run:
php bin/magento module:status Vendor_Extensions
If the module appears in the list of enabled modules, the installation was successful.
Result
After following these steps, you will have:
- A fully registered Magento 2 custom module.
- A module structure that follows Magento development standards.
- Upgrade-safe customization without modifying core files.
- A foundation for creating custom controllers, models, plugins, and observers.
- A better understanding of Magento's modular architecture.