Create the module & define dependencies
In this lesson, we will be building a module for Magento. We will start with a vanilla install of Magento and proceed with creating the necessary directories and files to build our module.
Setting Up the Module Directory
First, navigate to the
app/code directory. Create a new directory for our vendor name, which will be
Macademy, and our module name, which will be
Minerva. The module name is inspired by the Roman goddess of wisdom, as the module represents a database of frequently asked questions and answers.
Creating the registration.php File
The next step is to create a
registration.php file. In all PHP files, we will be declaring strict types, which is a commonly known best practice and recommended by Magento.
Next, import the
ComponentRegistrar class, and call its’
register function. This function accepts three arguments: a type, component name, and path. For the type, call
ComponentRegistrar again, and then call its module constant. Since we are creating a module, the name will be our vendor name
Macademy, followed by an underscore, and then the module name, which is
Minerva. This string will be used anytime Magento references the module in code.
Since our module files will all be in this directory, we will call the
__DIR__ constant in PHP, which is a reference to the current directory. This will register the module in Magento on the PHP level.
Creating the etc/module.xml File
To register the module with Magento on the configuration layer, we need another file named
etc/module.xml. Within this file, we will define a module root XML node, which is
config. It will have the no namespace schema location set to Magento framework’s
module.xsd file. These xsd files just validate the structure of the XML files to make sure we are creating it in a format that Magento expects to see.
config will come a module node, and then the name of our module which will be
Macademy_Minerva. In this case, we are going to open it so we can define some dependencies for our module, and we do that with the
sequence node. This sequence node expects any number of module nodes.
Every admin grid in Magento depends on both the
Magento_Backend module and
Magento_UI. So we will declare those upfront because we know they’re going to be dependent upon. This ensures that the Backend and UI modules are loaded before our module, which makes our module load last and have the highest level of precedence.
Enabling the Module
Finally, open up the terminal and enable this module by running the following command:
bin/magento module enable Macademy_Minerva
Assuming you are running either a
docker-magento setup or have cache clean enabled to automatically flush these caches. If not, you will also have to purge the cache. After running the command, confirm the module is enabled by running:
We can confirm that there are no disabled modules here, and that our module appears under the enabled module list.