This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

How to Create a Module in Magento 2 (A Developer’s Guide)

Updated on November 9, 2022

8 Min Read
Create Magento 2 Module

The architecture of the Magento system was designed to make the source code as modularized and extensible as possible. Customizing code usually means changing the behavior of the platform’s code. There’s a need for a Magento Module! In Magento 2, if you are following the best practices to update the source code, this is something you can reliably avoid most of the time.

Magento 2 module is the structural element that makes up the code base of the whole system. The module is essential in customizing core functionality according to your application requirements. This is useful when you have to add customized functionality.

In this article, you will learn how the Magento 2 module directory is structured and how to register and declare a module in your store.

What Is a Module in Magento 2?

According to merchants and extension developers, modules are the central unit of the Magento platform. It is a group of directories that contain the blocks, controllers, helpers, and models needed to create a specific store feature. It is the unit of customization in the Magento platform.

Magento modules can be created to perform multiple functions, from influencing user experience to changing storefront appearance. They can be installed, deleted, or disabled.

Move to a Faster Magento 2 Hosting

Cloudways offers advance caches to make your Magento store load faster along with free migration.

Structure for Creating a Module in Magento

To build a module in Magento 2, you need to understand the architecture of the module directory. Magento 2 architecture has two locations to create the module: app/code folder and the vendor folder.

In Magento 2, all the core modules located at vendor/magento/magento-* folders come under the installation of Magento 2. If you are building any overriding existing functionality or customizing the core module, the best practice is to select the app/code directory and commit the repository of the application.

Let’s take a quick overview of the source code folder structure to find where we need to place our code. To create a Magento 2 module, first, we need to set up the module’s structure by creating folders.

Module directory structure

  • Cloudways: namespace name.
  • Mymodule: module name.
  • Block: it’s a foundational building unit for layouts in Magento. It links a PHP block class (which contains logic) and a template (which renders content).
  • Model: for Models and ResourceModels
  • Observer: usually used when such an event is fired, the observer instantiates a Model to handle the necessary business logic for such an event.
  • Controller: controls the flow of application execution.
  • Helper: helper classes hold the code used in more than one application layer. For example, in the Cms module, helper classes are responsible for preparing HTML for presentation to the browser.
  • Setup: contains the migration and upgradation classes for schema and data creation of the database.
  • Index: controller name of the module and contains the action file.
  • etc: contains the configuration file of the module.
  • etc/Frontend: contains the router file.
  • view/Frontend: Contains Layout and Templates Folder.
  • view/Frontend/Layout: contain XML file.
  • view/Frontend/Templates: contain .phtml file.
  • Composer.json: used for the updating of product editions like the module. This file must be placed in the root directory of the module.

Below you’ll find the structure of the vendor/magento core module responsible for handling the Magento core functionality. Note that how Magento 2 module core code dependencies are inside the composer vendor folder.

magento 2 module vendor

Alright, now let’s do something more practical, shall we? Here’s the step-by-step tutorial to create the Magento 2 module.

Experience the Cloudways Magento 2 Demo Store – No tech skills needed!

Experience a fully functional Magento 2 store built on top of renowned Cloudways hosting to deliver the fastest speeds.

Step 1: Create the Magento 2 Module Directory

Let’s create the folder in the directory app/code to build the extension in a given structure defined as VendorName_ModuleName. We created Cloudways_Mymodule, where the first part is the name of the vendor provider and the second part is the module’s name.

app/code/Cloudways/Mymodule

To use the command to create a folder:

  1. cd to the root folder
  2. mkdir app/code/Cloudways
  3. mkdir app/code/Cloudways/Mymodule

magento-module-structure

create-magento-module-directory

Step 2: Declare the Magento 2 Module

Declare the created Magento 2 module by using the configuration file. During the Magento 2 module development, the file system searches for the module’s configuration found in the, etc directory of the module. Create the configuration file module.xml.

This file contains information about the Module Name, Module Version, and dependencies of other modules. The code will look like this:

<?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="Cloudways_Mymodule" setup_version="1.0.0"></module>

</config>

Let’s discuss the code a bit more to understand it better.

<config>: Root node for configuration of Magento module.

<module>: Basic information about the Magento module will be provided here.

Name attribute in <module>: Namespace_Modulename the module name will be Cloudways_Mymodule.

Setup_version in <module>: This describes the current version of the database and data indicated by the module and tells Magento when to run the migration scripts. The version can help upgrade and install table schema.

Dependencies: If one module has some extended functionality depending on another Magento core module, the declaration is in the module.xml file. To mention the dependencies, use the following code:

<module name="Cloudways_Mymodule" setup_version="1.0.0">

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

…..

</module>

Creating a module in Magento 2 is essential in declaring the dependencies of other modules in the module.xml file.

Step 3: Register the Created Module in Magento 2

The module has to be registered in the Magento 2 system using the Magento Component Registrar class that defines how to locate the module. Continuing our module, create the file registration.php in the module root directory:

app/code/Cloudways/Mymodule/registration.php

The code will look like this:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

\Magento\Framework\Component\ComponentRegistrar::MODULE,

'Cloudways_Mymodule',

__DIR__

);

This file calls the register method of ComponentRegistrar class with two parameters, the string Module tells the type we are going to register, and the other is our module name Cloudways_Mymodule. This step holds important information in Magento 2 module creation.

  • Cloudways: namespace name.
  • Mymodule: module name.

This standard file follows the same pattern for all modules; only the module name varies.

Step 4: Run the Command

The steps above should result in the creation of a simple module. To notify Magento of its presence, run the commands below:

php bin/magento setup:upgrade
php bin/magento setup:di:compile

This is the output of our created module: Cloudways_Mymodule.

Step 5: Enable Magento 2 Module

Use the following command line to check if the module is enabled or disabled:

php bin/magento module:status

Magento module status

Status disable/enable Magento

If you find your module in the disabled list, then you have to enable it by using the following command:

php bin/magento module:enable Cloudways_Mymodule

You have enabled the module for the first time. Recheck the status and confirm the module is enabled. Also, you can open app/etc/config.php and check the file content for the Cloudways_Mymodule key, whose value must be 1.

magento-module-config

There you go! You have successfully created a module in Magento 2. After enabling the module, recheck the status of modules with the command line mentioned before.

Create a Magento 2 Module Route

Now we’ll start implementing the route and controller to display some content in our created module. To define a route in the front-end, we need to create the file app/code/Cloudways/Mymodule/etc/frontend/routes.xml with the following source code:

<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

    <router id="standard">

        <route frontName="myroute" id="myroute">

            <module name="Cloudways_Mymodule"/>

        </route>

    </router>

</config>

Let’s understand a bit more about the source code. In Magento 2, the structure of the URL contains three parts.

  1. frontNameroute_id
  2. controller name – index
  3. action name – index

This will look like this:

http://cloudways.com/index.php/frontname/controller/action

So, in our example, we are defining the route of the frontend area as defined in the routes.xml file. There are two attributes of the route tag: the Id and frontName. The ID should be unique to identify the router tag. Also, note it’s the best practice to keep the ID and frontName the same to avoid confusion.

Create a Controller and Action

Now we are telling Magento that our module will use the frontName defined in the routes.xml file. To create a Controller and action, make the folder in this path: app/code/Cloudways/Mymodule/Controller/Index/Index.php.

Use the source code below to create the controller action:

<?php


namespace  Cloudways\Mymodule\Controller\Index;


use \Magento\Framework\App\Action\Action;

use \Magento\Framework\View\Result\PageFactory;

use \Magento\Framework\View\Result\Page;

use \Magento\Framework\App\Action\Context;

use \Magento\Framework\Exception\LocalizedException;


class Index extends Action

{




    /**

     * @var PageFactory

     */

    protected $resultPageFactory;




    /**

     * @param Context $context

     * @param PageFactory $resultPageFactory

     *

     * @codeCoverageIgnore

     * @SuppressWarnings(PHPMD.ExcessiveParameterList)

     */

    public function __construct(

        Context $context,

        PageFactory $resultPageFactory

    ) {

        parent::__construct(

            $context

        );

        $this->resultPageFactory = $resultPageFactory;

    }




    /**

     * Prints the statement

     * @return Page

     * @throws LocalizedException

     */

    public function execute()

    {

        echo "My module works";

        exit;

    }

}

After this, please run php bin/magento cache: clean to check the result.

Your URL now should be:

http://<yourhost.com>/myroute/index/index

Example: https://magento-761105-2575467.cloudwaysapps.com/myroute/index/index

Note: After finishing all steps, the output My module works should be displayed in your browser when you open the URL.

magento-module-results

Now, if you open the URL, you will get a 404, so let’s fix that. First, you need to run the php bin/magento cache:flush command after that, if still facing the issue, you can refer to how to solve the Magento problem.

Summary

This article taught us how to create a module in Magento 2. Hopefully, this article has provided you with all the details to run the development stage of the Magento 2 module. In the next part, we will learn how to create block and layout xml in Magento 2.

Please leave a comment below if you have any problems or would like to add to the discussion!

Q1. What is module.xml in Magento?

In Magento 2, the component required to declare the name and existence in the module directory structure is the module.xml file. Add the module.xml file to the /etc folder of your module directory.

<?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="Vendor_ComponentName"/>

</config>

The module.xml examines the declaration of the Name of your component and setup_version if required to manage the setup of the installation and upgrade processes for your component. It also examines the dependencies of other modules if your module depends on other components.

Q2. How can you call a module in Magento 2?

In Magento 2, the modules are in the app/code directory with the structure Vendor/ModuleName, such as Cloudways/Mymodule; follow the below process to create:

  1. Create the Cloudways/Mymodule Folder
  2. Declare the module by creating the file, etc/module.xml
  3. Register the created module by creating the file registration.php.
  4. Run the Command: php bin/magento setup:upgrade, php bin/magento setup:di:compile, php bin/magento cache:flush
  5. Check the module status module by php bin/magento module:status

Q3. Where are Magento modules stored?

Magento 2 modules are located in two possible locations: the app/code and vendor/module* (for Composer). The vendor directory contains all the core modules during the installation with PSR standard format.

If you are creating a module or improving the functionality of the existing modules, the recommended location is app/code. Create the directory as app/code/Cloudways/Mymodule directory and the required directories for the module.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Jyotishna Kumari

Jyotishina is the Magento Community Expert at Cloudways and has 4 years of experience in web development. She has worked on e-commerce sites since the turn of the millennium and was working with Magento before version 1 was released. She loves to travel and explore new ideas whenever she finds time. Get in touch with her at [email protected].

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now