How to create a simple Hello World module for Magento 2

Magento 2 Module development or Magento 2 Hello World trends is increase rapidly while Magento release official version. That why we - Mageplaza - are wring about a topic that introduces how to create a simple Module.

As you know, the module is a directory that contains blocks, controllers, models, helper, etc - that are related to a specific business feature. The etc folder contains admin ACL, admin menu, configuration . In Magento 2, modules will be live in app/code directory of a Magento installation, with this format: app/code/<Vendor>/<ModuleName>. Now we will follow this steps to create a simple module which work on Magento 2 and display Hello World.

Looking for
Customization & Development Services?

8+ years of experiences in e-commerce & Magento has prepared us for any challenges, so that we can lead you to your success.

Get free consultant
development service

Main components in Magento 2 Hello Word

Main components in Magento 2 Hello Word

Before we walk you through how to create a simple Hello World module for Magento 2, you need to understand the key components in Magento 2 Hello Word to find where we need to place our code.

  • 1. Mageplaza: It refers to the namespace name. Namespace helps to organize code and prevent naming conflicts. Mageplaza could be your custom namespace.

  • 2. Mymodule: This represents the module name. In Magento 2, modules encapsulate specific functionality. You’ll create your custom module under this name.

  • 3. Block: A block in Magento is a basic component for creating layouts. It connects a PHP block class that handles the logic with a template that renders the content. Blocks handle data processing and interact with templates.

  • 4. Model: Models and Resource Models are essential for data handling. Models represent business logic, while Resource Models interact with the database.

  • 5. Observer: Observers are used when specific events are fired within Magento. An observer instantiates a Model to address necessary business logic related to that event.

  • 6. Controller: Controllers control the flow of application execution. They handle requests and route them to appropriate actions.

  • 7. Helper: Helper classes hold reusable code used across different application layers. For instance, in the CMS module, helper classes prepare HTML for presentation in the browser.

  • 8. Setup: The Setup component includes migration and upgrade classes for schema and data creation in the database during module installation.

  • 9. Index: This likely refers to the controller name within your module, which contains action files.

  • 10. etc: The etc directory holds the configuration files for the module. It defines routes, dependencies, and other settings.

  • 11. etc/Frontend: Within this directory, you’ll find the router file for frontend routes.

  • 12. view/Frontend: It includes the Layout and Templates folders for frontend views.

  • 13. view/Frontend/Layout: This directory contains XML files defining the layout structure for your module.

  • 14. view/Frontend/Templates: Here, you’ll find .phtml files responsible for rendering HTML content.

  • 15. Composer.json: This file is crucial for updating product editions (like your module). It must be placed in the root directory of your module.

Basic Topics

Create Hello World module for Magento 2

Now we will follow this steps to create a simple module which work on Magento 2 and display Hello World. To create Hello World module, you need to complete the following high-level steps:

  • Step 1: Create the folder of Hello World module
  • Step 2: Create etc/module.xml file
  • Step 3: Create etc/registration.php file
  • Step 4: Enable the module

Step 1: Create the folder of Hello World module

Name of the module is defined as VendorName_ModuleName. First part is name of the vendor and last part is name of the module: For example: Magento_HelloWorld, Mageplaza_PdfInvoice. Focus on following guide to create the folders:

  app/code/Mageplaza/HelloWorld

Step 2: Create etc/module.xml file.

Then, it is necessary to create etc folder and add the module.xml file

  app/code/Mageplaza/HelloWorld/etc/module.xml

Contents would be:

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

Step 3: Create etc/registration.php file

In this step, we will add registration.php as following guide:

  app/code/Mageplaza/HelloWorld/registration.php

Contents would be:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
	\Magento\Framework\Component\ComponentRegistrar::MODULE,
	'Mageplaza_HelloWorld',
	__DIR__
);

Step 4: Enable the module

Finish the step 3, we have already created the HelloWorld module. And we will enable this module in this step

After create the module if you run the command as:

  php bin/magento module:status

You should see the module is disable now:

List of disabled modules: Mageplaza_HelloWorld

Follow exact guide to enable the module right now, let run the command as:

  php bin/magento module:enable Mageplaza_HelloWorld

Or other way, you can access the file:

  app/etc/config.php

You will see a long list of modules there, just add your module as well

  ...
  'Mageplaza_HelloWorld' => 1, 
  ...

Your module should be available now.

After this step, when you open your website in browser you will get an error saying

Please upgrade your database: Run bin/magento setup:upgrade from the Magento root directory.

Let run the command:

  php bin/magento setup:upgrade

After complete,when you open your website in browser you will see the layout of the website is broken.

magento 2 broken upgrade

Please run the deloy command line to fix it.

php bin/magento setup:static-content:deploy

After deploy completed, you can also see your module from backend at System Configuration -> Advanced -> Disable Modules Output.

Step 5: Create a Controller

Now, we will create a controller to test module.

Before create a controller, we will create a route for HelloWorld module.

Route’s in magento are divided into 3 parts: Route frontname, controller and action as following example:

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

To add route, it is necessary to create routes.xml file

Step 5.1: Create a routes

app/code/Mageplaza/HelloWorld/etc/frontend/routes.xml

since this is a frontend route, we added it in frontend/ folder else we need to add it to adminhtml/ folder

Content would be:

<?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="helloworld" id="helloworld">
            <module name="Mageplaza_HelloWorld"/>
        </route>
    </router>
</config>

After defining the first part of the route, the URL will be displayed as:

  http://<yourhost.com>/helloworld/*

E.g: http://localhost/helloworld/*

Then, we will continue to create the controller and action

Step 5.2: Create a Action in Controller

The folder and file you need to create is:

app/code/Mageplaza/HelloWorld/Controller/Index/Test.php

Contents would be:

<?php
namespace Mageplaza\HelloWorld\Controller\Index;

class Test extends \Magento\Framework\App\Action\Action
{
	protected $_pageFactory;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $pageFactory)
	{
		$this->_pageFactory = $pageFactory;
		return parent::__construct($context);
	}

	public function execute()
	{
		echo "Hello World";
		exit;
	}
}

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

Your URL now should be as:

 http://<yourhost.com>/helloworld/index/test

Hello World

FAQs

What is module.xml in Magento?

Module.xml is a configuration file that defines a Magento module. It offers important information about the module, such as its name, version, and dependencies. Magento modules follow a folder structure that includes the vendor (which is a group of modules) and the module itself. The module.xml file is located within this structure and helps Magento understand the properties and requirements of the module.

Can I create multiple modules within the same Magento 2 instance?

Yes, Magento 2 allows you to create and manage multiple modules within the same Magento 2 instance. Modules in Magento are like building blocks that allow you to extend or modify the core system’s functionality.

Where are Magento modules stored?

In Magento 2, modules are stored in two locations:

  • app/code: This directory contains the default modules that come with Magento. Each module resides in a subdirectory under app/code. For example, if you create a custom module named “Mymodule,” you would place it in the app/code/Cloudways/Mymodule directory. This is the recommended location for custom modules you create or enhance.

  • vendor/module: If you’re using Composer (which is the standard practice), modules installed via Composer are stored in the vendor directory. These modules are typically third-party extensions or community-contributed modules. The vendor directory contains all the core modules during the initial installation.

Is it possible to create a module that integrates with third-party APIs?

Absolutely! Magento 2 provides robust APIs for integrating with third-party services, making it easy to create modules that enhance their functionality and save development time.

Are there any resources available for further learning about Magento 2 module development?

Yes, Magento’s official documentation and community forums are incredible resources for learning more about module development in Magento 2. Additionally, there are many online tutorials and courses available for developers looking to deepen their knowledge.

After finish all steps, the output Hello World should be displayed in your browser when you open the URL.

We hope our guide is very useful and effective for you. Any questions, feel free to leave a commend below.

In the next tutorial, you will learn how to create a controller.

Looking for
Upgrade Services?

Upgrade your Magento 2 store to the latest version for new features and security - with the help of our dedicated experts.

Upgrade now
upgrade service
Image Description
With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.

People also searched for

  • Magento 2 Module Development
  • magento 2 simple module
  • magento 2 extension development
  • magento 2 hello world
  • create module in magento 2
  • magento 2 create extension
  • magento 2 custom module
  • magento 2 extension tutorial
  • magento 2 module creation
  • magento 2 create simple module
  • magento 2 module tutorial
  • magento 2 create module
  • magento 2 create custom module
  • how to create module in magento 2
  • create magento 2 module
  • create module magento 2
  • magento 2 module development
  • magento2 create module
  • Magento 2 hello world
  • magento 2 extension development
  • magento 2 tutorial for beginners step by step
  • magento 2 tutorial for developer
  • 2.3.x, 2.4.x
x