How to create a custom module in Magento 2
There are two layers in Magento 2 that can be used for adding custom functionality to a project. Small additions and frontend changes can be done by extending any existing theme. With this approach you can mainly change the layout, override template and asset files. Low level changes have to be done inside a custom module. It does not matter how small or big these changes are.
The anatomy of a module
Dummy module, that does "absolutely nothing" requires the right folder structure with 2 files:
module.xml. It only becomes installable.
└── Acme └── Example ├── etc │ └── module.xml └── registration.php
Custom modules can be placed inside the
app/code folder or be installed using composer. In this example
Acme represents the vendor and
Example is the concrete name of the feature(s). Modules root namespace is
It is always a good practice to use meaningful namespaces. For a blog module
YourCompany\Blogwould be an excellent choice.
registration.php is used mainly for telling Magento the correct path of the module.
<?php use Magento\Framework\Component\ComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Acme_Example', __DIR__);
module.xml specifies the version. When module is used only privately, there is no need to bump the version after every change. Versioning is needed when the module needs to upgrade a database scheme or similar.
<?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="Acme_Example" setup_version="0.0.1" /> </config>
Installing the module
It is impossible to be a Magento 2 developer without some command line interface skills. Everything is in cli!
After the module (or modules) has been placed inside the
app/code folder, following command inside the projects root folder will make the install:
php bin/magento setup:upgrade