← Back to Blog

Magento 2 Custom Module Development: A Complete Guide

Magento 2 is one of the most powerful e-commerce platforms available today. One of its greatest strengths is its modular architecture, which allows developers to extend functionality through custom modules. In this guide, we'll walk through the complete process of creating a custom module in Magento 2.

Prerequisites

Before we begin, make sure you have:

  • A working Magento 2 installation (version 2.4.x recommended)
  • PHP 8.1 or higher
  • Composer installed
  • Basic understanding of PHP and MVC architecture

Understanding Magento 2 Module Structure

A Magento 2 module follows a specific directory structure. Here's what a typical module looks like:

code
app/code/Vendor/ModuleName/
ā”œā”€ā”€ etc/
│   ā”œā”€ā”€ module.xml
│   └── routes.xml
ā”œā”€ā”€ Controller/
ā”œā”€ā”€ Model/
ā”œā”€ā”€ view/
│   └── frontend/
│       ā”œā”€ā”€ layout/
│       └── templates/
ā”œā”€ā”€ registration.php
└── composer.json

Step 1: Create the Module Registration File

First, let's create our module. We'll build a simple "Hello World" module under the vendor name Softinity and module name HelloWorld.

Create the file app/code/Softinity/HelloWorld/registration.php:

php
<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Softinity_HelloWorld',
    __DIR__
);

This file registers your module with Magento's component registrar system.

Step 2: Create the Module Declaration

Create app/code/Softinity/HelloWorld/etc/module.xml:

xml
<?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="Softinity_HelloWorld" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Store"/>
        </sequence>
    </module>
</config>

The sequence node defines dependencies - modules that must load before yours.

Step 3: Create a Frontend Route

To make our module accessible via URL, we need to define a route. Create app/code/Softinity/HelloWorld/etc/frontend/routes.xml:

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="helloworld" frontName="helloworld">
            <module name="Softinity_HelloWorld"/>
        </route>
    </router>
</config>

This creates a route accessible at yourstore.com/helloworld.

Step 4: Create a Controller

Controllers handle requests and return responses. Create app/code/Softinity/HelloWorld/Controller/Index/Index.php:

php
<?php
namespace Softinity\HelloWorld\Controller\Index;

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

class Index implements HttpGetActionInterface
{
    protected PageFactory $pageFactory;

    public function __construct(PageFactory $pageFactory)
    {
        $this->pageFactory = $pageFactory;
    }

    public function execute()
    {
        $page = $this->pageFactory->create();
        $page->getConfig()->getTitle()->set(__('Hello World'));
        return $page;
    }
}

Note: In Magento 2.4+, controllers should implement action interfaces like HttpGetActionInterface instead of extending the deprecated Action class.

Step 5: Create the Layout File

Layouts define the structure of your page. Create app/code/Softinity/HelloWorld/view/frontend/layout/helloworld_index_index.xml:

xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template"
                   name="helloworld.content"
                   template="Softinity_HelloWorld::hello.phtml"/>
        </referenceContainer>
    </body>
</page>

Step 6: Create the Template

Templates contain the actual HTML output. Create app/code/Softinity/HelloWorld/view/frontend/templates/hello.phtml:

php
<?php
/** @var \Magento\Framework\View\Element\Template $block */
?>
<div class="helloworld-container">
    <h1><?= $block->escapeHtml(__('Hello World from Softinity!')) ?></h1>
    <p><?= $block->escapeHtml(__('This is a custom Magento 2 module.')) ?></p>
</div>

Step 7: Enable the Module

Now let's enable our module. Run these commands from your Magento root directory:

bash
# Enable the module
bin/magento module:enable Softinity_HelloWorld

# Run setup upgrade
bin/magento setup:upgrade

# Compile DI (for production mode)
bin/magento setup:di:compile

# Deploy static content (for production mode)
bin/magento setup:static-content:deploy -f

# Clear cache
bin/magento cache:clean

Step 8: Test Your Module

Visit https://yourstore.com/helloworld and you should see your Hello World page!

Best Practices

Here are some best practices to follow when developing Magento 2 modules:

  1. Use Dependency Injection - Always inject dependencies through constructors rather than using ObjectManager directly.
  2. Follow Magento Coding Standards - Use PSR-4 autoloading, follow naming conventions, and run code quality tools.
  3. Use Plugins Wisely - Plugins (interceptors) are powerful but can impact performance. Use them only when necessary.
  4. Implement Interfaces - Code against interfaces rather than concrete implementations for better flexibility.
  5. Write Unit Tests - Magento 2 has excellent testing support. Write tests for your business logic.

Conclusion

You've now learned the fundamentals of Magento 2 module development! This foundation will allow you to build custom functionality for any e-commerce requirement. Key takeaways:

  • Magento 2 modules follow a strict directory structure
  • Registration and declaration files are required
  • Controllers handle requests, layouts define structure, templates render output
  • Always follow Magento best practices for maintainable code

Need help with your Magento 2 project? Contact Softinity for expert e-commerce development services.