Magento module registration file

Modules need two files in order to be registered & enabled in Magento.

The first is in the root of the module, and is named registration.php. This is the file that exposes this as a Magento module at the PHP-layer.

<?php declare(strict_types=1);

use Magento\\Framework\\Component\\ComponentRegistrar;

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

It’s a PHP best practice nowadays to declare strict types at the top of each of your PHP files with declare(strict_types=1);. Doing so ensures that variables have a specified type, otherwise a TypeError is thrown, and stops the execution of further processing.

Let’s call the ComponentRegistrar class, which comes from Magento Framework’s Component folder. This class has a static ::register() function that we’ll call to register the module.

You can step into classes, functions, and variables by holding down Command on the keyboard, or Ctrl on Linux/Windows, and clicking on the appropriate block of code. Let’s command click into the register function and see what’s going on here.

This function accepts three parameters, the type of the component, a fully-qualified component name, and the absolute path to the component.

Let’s start with the type. The type is a string, and if we scroll up in this ComponentRegistrar class we will see the different types of components we can pass in. Since we are declaring a module, we can just use this 'module' string.

These class constants are declared for a reason though. Rather than hard-coding the string, let’s instead call the class constant directly with ComponentRegister::MODULE. Note how we get a nice preview of what we are calling directly within PhpStorm.

Our next argument is the componentName. Again, this is the fully-qualified component name.

The fully-qualified component name for a module is the vendor name and the module name, concatenated with an underscore. So this will be Macademy_Blog. This fully-qualified component name is used in many places through Magento.

Our last argument is the absolute path to the component. We never want to hard-code a string here to make our code more portable. But, this path will always be the “current directory” that we are in.

We can use the __DIR__ constant of PHP to specific the current directory of this file. If we command or control click into this constant, we can confirm what this constant does and how it is implemented.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock