How to Create a Module in Magento 2
Magento 2 follows a modular architecture where all custom functionality is built using modules. A module is the core unit of customization that allows you to extend or modify Magento behavior without touching core files.
What Is a Module in Magento 2?
A Magento 2 module is a collection of PHP classes, XML configuration files, layouts, and templates grouped under a unique namespace. Modules can be enabled, disabled, or removed independently.
- Add new features or pages
- Modify frontend or admin behavior
- Integrate third-party services
- Extend core functionality safely
Module Location
Custom modules should be placed inside the app/code directory
using the format:
VendorName/ModuleName
Example:
app/code/Hikmadh/Mymodule
Basic Module Structure
app/code/Hikmadh/Mymodule
│── Controller
│── Block
│── Model
│── Helper
│── Observer
│── etc
│ └── frontend
│── view
│ └── frontend
│ ├── layout
│ └── templates
│── registration.php
│── composer.json (optional)
Step 1: Create module.xml
The module.xml file declares the module name and version.
<?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"/>
</config>
Step 2: Register the Module
Magento must know where your module is located. This is done using
registration.php.
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Hikmadh_Mymodule',
__DIR__
);
Step 3: Enable the Module
php bin/magento setup:upgrade
php bin/magento module:enable Hikmadh_Mymodule
php bin/magento cache:flush
Step 4: Create Frontend Route
Define a frontend route using routes.xml.
<?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="myroute" frontName="myroute">
<module name="Hikmadh_Mymodule"/>
</route>
</router>
</config>
Step 5: Create Controller
Create a controller action to verify the module is working.
<?php
namespace Hikmadh\Mymodule\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action
{
public function __construct(Context $context)
{
parent::__construct($context);
}
public function execute()
{
echo 'My module works';
exit;
}
}
Access the Module
http://your-domain.com/myroute/index/index
If everything is configured correctly, the output “My module works” will appear in the browser.
Conclusion
Creating a module in Magento 2 is the foundation of customization. By following Magento’s modular structure, you ensure clean code, upgrade safety, and long-term scalability.