How to Create a Custom Module in Magento 2 (Step-by-Step Guide)

Magento 2Module DevelopmentTutorial
Tested: every file in this guide was checked on Magento Open Source 2.4.8-p3 with PHP 8.4. The PHP passes php -l, the XML validates against Magento's own XSD schemas, and the module passes the official Magento2 coding standard (PHPCS) with 0 errors and 0 warnings.

Almost every Magento 2 customisation lives in a module. Whether you are adding a checkout field, a custom report or an ERP integration, the starting point is the same small set of files. In this guide we will build a simple module called Vendor_HelloWorld that adds a new frontend page at /helloworld, then look at the best practices that keep custom modules clean and upgrade-safe.

1. Module folder structure

Custom modules live in app/code/<Vendor>/<Module>. For our example, create this structure:

app/code/Vendor/HelloWorld/
├── registration.php
├── composer.json
├── etc/
│   ├── module.xml
│   └── frontend/
│       └── routes.xml
├── Controller/
│   └── Index/
│       └── Index.php
└── view/
    └── frontend/
        ├── layout/
        │   └── helloworld_index_index.xml
        └── templates/
            └── hello.phtml

2. registration.php

This file tells Magento the module exists and where it lives:

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

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

3. etc/module.xml

The module declaration. The <sequence> element makes sure modules you depend on are loaded first:

<?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_HelloWorld">
        <sequence>
            <module name="Magento_Store"/>
        </sequence>
    </module>
</config>

4. composer.json

Not strictly required for app/code, but it documents dependencies and lets you install the module with Composer later:

{
    "name": "vendor/module-hello-world",
    "description": "Hello World example module",
    "type": "magento2-module",
    "require": { "php": "~8.1.0||~8.2.0||~8.3.0||~8.4.0" },
    "autoload": {
        "files": ["registration.php"],
        "psr-4": { "Vendor\\HelloWorld\\": "" }
    }
}

5. Add a frontend route

etc/frontend/routes.xml maps the URL prefix helloworld to our module:

<?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="Vendor_HelloWorld"/>
        </route>
    </router>
</config>

6. Create the controller

Magento URLs follow the pattern frontName/controller/action, so /helloworld resolves to Controller/Index/Index.php. Modern controllers implement an HTTP-method interface instead of extending the old Action class:

<?php
declare(strict_types=1);

namespace Vendor\HelloWorld\Controller\Index;

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

/**
 * Renders the Hello World page.
 */
class Index implements HttpGetActionInterface
{
    /**
     * @param PageFactory $pageFactory
     */
    public function __construct(
        private readonly PageFactory $pageFactory
    ) {
    }

    /**
     * Render the page with a custom title.
     *
     * @return Page
     */
    public function execute(): Page
    {
        $page = $this->pageFactory->create();
        $page->getConfig()->getTitle()->set(__('Hello World'));
        return $page;
    }
}

7. Layout and template

The layout handle is routeId_controller_action, so the file is view/frontend/layout/helloworld_index_index.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="Vendor_HelloWorld::hello.phtml"/>
        </referenceContainer>
    </body>
</page>

And the template, view/frontend/templates/hello.phtml. Always escape output:

<?php /** @var \Magento\Framework\Escaper $escaper */ ?>
<h2><?= $escaper->escapeHtml(__('Hello from my first Magento 2 module!')) ?></h2>

8. Enable the module

Run these commands from the Magento root:

bin/magento module:enable Vendor_HelloWorld
bin/magento setup:upgrade
bin/magento cache:flush

In production mode you also need bin/magento setup:di:compile and bin/magento setup:static-content:deploy. Now open https://your-store.com/helloworld and you should see your page.

Best practices for production modules

  • Never edit core files or copy core classes. Use plugins, observers or preferences to change behaviour.
  • Use dependency injection: request what you need in the constructor. Do not call ObjectManager directly in your classes.
  • Use declarative schema (etc/db_schema.xml) for database tables and data patches for data changes, instead of old install/upgrade scripts.
  • Define service contracts (interfaces in Api/) for anything other modules or APIs will use.
  • Make it configurable with etc/adminhtml/system.xml and sensible defaults in etc/config.xml.
  • Escape all output in templates and validate all input in controllers.
  • Run the coding standard: vendor/bin/phpcs --standard=Magento2 app/code/Vendor/HelloWorld. It flags missing doc comments too, which is why the controller above has them; the Adobe Commerce Marketplace runs the same checks on every extension.

Next steps

From here you can add an admin configuration section, a database table with declarative schema, or a REST API endpoint. If you need a production-grade module built for your store, take a look at my Magento 2 custom module development service, or browse my 62 Marketplace extensions to see what is already available.

Sources

Sukumar Gorai

Sukumar Gorai

Adobe Certified Magento Expert and Technical Lead with 15+ years of experience and 62 extensions on the Adobe Commerce Marketplace. More about me →

Need help with this?

Upgrade-safe custom modules for checkout, pricing, B2B workflows, integrations and admin tools.

Custom Module Development
Available for new projects

Have a Magento project in mind?

Tell me about your store and what you need. I reply to every enquiry within one business day.

Adobe Certified Expert

Adobe Commerce Developer certification, verified on Credly.

15+ years of Magento

From Magento 1 to Magento 2.4.x, Adobe Commerce and Hyvä.

62 Marketplace extensions

Each one reviewed and approved by Adobe.