Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

The first module

A module is a folder with code and configuration that Magento loads as a single unit. A developer writes all their code in modules. Magento has no command for creating a module: the two required files are created by hand.

Where a module lives

Your modules are in app/code/Vendor/Module. The vendor is the name of a company or an author; it separates your modules from other people's. Let's create the Hello module of the Acme vendor:

app/code/Acme/Hello/
├── registration.php
└── etc/
    └── module.xml

The full module name is Acme_Hello, and the namespace of its classes is Acme\Hello.

The registration.php file

Create the file app/code/Acme/Hello/registration.php:

// app/code/Acme/Hello/registration.php
use Magento\Framework\Component\ComponentRegistrar;
 
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Acme_Hello', __DIR__);

The file tells Magento that this folder contains a module named Acme_Hello. In the real file the first line is the PHP opening tag.

The module.xml file

Create the file app/code/Acme/Hello/etc/module.xml:

<?xml version="1.0"?>
<!-- app/code/Acme/Hello/etc/module.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Acme_Hello"/>
</config>

The file declares the module. The name in the name attribute must match the name from registration.php.

Enabling

bin/magento module:enable Acme_Hello
bin/magento setup:upgrade
bin/magento cache:clean

The first command writes the module into app/etc/config.php, the second registers it in the database, the third cleans the cache.

Checking

bin/magento module:status Acme_Hello

The command prints Acme_Hello : Module is enabled. The module does nothing yet — it gets a page in the following lessons.

Dependencies on other modules

If a module uses or changes another module, this is stated in the sequence section:

<module name="Acme_Hello">
    <sequence>
        <module name="Magento_Catalog"/>
    </sequence>
</module>

Now Magento_Catalog loads earlier, and the configuration of Acme_Hello is applied on top of its configuration. After changing sequence, run bin/magento setup:upgrade again.

Disabling

bin/magento module:disable Acme_Hello

The module stops loading, but its files and tables stay in place.

Common mistake

The files are created, but the module does not work and module:status lists it as disabled. A new module is not picked up on its own: module:enable and setup:upgrade are required. The second typical cause is letter case: the folder app/code/acme/hello and the name Acme_Hello do not match on a Linux server.

Thanks for reading!

Donate to the site — we work hard for you.