A Beginners guide: Creating your first Magento 2 Module

Hi,

In this series of guides, I am going to show you how to get started customising Magento 2 for your exact requirements.

The whole of Magento is comprised of “modules”. These are custom units of functionality that are added to the framework. Examples of these units are:

  • CMS (module-cms) – basic CMS functionality that allows a user to create static pages.
  • Catalog (module-catalog) – this is related to all functionality for Product and Product Category management
  • Inventory (module-inventory) – this relates to inventory management for Products
  • Theme (module-theme) – controls functionality for the theme, refer to this for when creating custom themes.

For the full list of Magento core modules, this can be found in /vendor/magento. So, when we want to consider customising Magento’s core functionality we can use this folder to refer to. Please note – we must never make changes to any code in here.

In this guide, I’m going to show you how to create the basic Skeleton for a Module.

Step 1. Create the required Directory Structures

Using the command line, navigate to the root directory of your Magento installation and create the following folders:

  • app/code/Johnadavies
  • app/code/Johnadavies/Demo
  • app/code/Johnadavies/Demo/etc

Replace “Johnadavies” with the name of your company and “Demo” with an appropriate name for the new functionality you’re introducing such as “Postcode” if you were creating a module for custom handling Postcodes.

Step 2. Let Magento know of your Module.

In app/code/Johnadavies/Demo/etc create file called module.xml and place the following code in it.

<?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="Johnadavies_Demo" setup_version="0.0.1">
     <module name="Johnadavies_Demo" setup_version="1.0.0" />
</config>

In future you will probably need to add to this depending on what you’re module is going to do.

Next we need to create a file called /app/codeJohnadavies/Demo/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Johnadavies_Demo',
    __DIR__
);

This file tells Magento how your new module should be referred to.

Step 3. Activate your Module

Finally go to the root of your Magento site on the command line and run the following command.

$php bin/magento setup:upgrade

This makes Magento become aware of your new module. To see if its worked simply go to /app/etc/confi.php and open it, in there you should see a line that looks like this:

'Johnadavies_Demo' => 1,

Congratulations – your new Magento Module is Active!

Your new module is now active and running! (although not doing anything 😉 )

Leave a Reply

Your email address will not be published. Required fields are marked *