How to create a simple Hello World module in Magento 2?

Creating a Simple Hello World Module using Magento 2 is the Entry point for Learning Magento module structure.

A simple Module to display, Hello World in the browser is used for Beginner of Magento Developer who wants to explore Magento 2 in depth.

You must need to create two entry point files registration.php and module.xml files to define the Custom Module.

    • registration.php — Used to Register New Module In Magento 2 System.
    • module.xml — XML file defines our module name.

The module is simply residing in the app/code folder of the Magento instance.

Just Create a Folder under the app/code,
For example, We kept Package Name as Rbj and the Module Name as Training.
In our demo, we have kept Packagename_Modulename as Rbj_Training.

Now start with basic module creation, Registration.php file is to register our module.  Create a registration.php file,

Full Path,  app/code/Rbj/Training/registration.php,

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

Create a module.xml file,
app/code/Rbj/Training/etc/module.xml,

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

In the above file keep the module tag name attribute equal to your {Packagename_Modulename}

Now create a routes.xml file,
app/code/Rbj/Training/etc/frontend/routes.xml,

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

The frontName attribute is the first part of our custom URL. Default URL structure for Magento 2 like,  <frontName>/<areaControllerFolderName>/<controllerClass>

Where areaControllerFolderName is your area’s controller Folder Name.
An area might be the front or admin area.

In our case, <areaControllerFolderName> equals Index and   <controllerClass> equals Training for our Module.

Create <controllerClass>,
app/code/Rbj/Training/Controller/Index/Training.php

<?php
declare(strict_types=1);

namespace Rbj\Training\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\PageFactory;

class Training extends Action implements HttpGetActionInterface
{
    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param Context  $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return ResultInterface
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        // Add page title
        $resultPage->getConfig()->getTitle()->set(__('Training Module'));
        return $resultPage;
    }
}

In Magento 2 Controller file with execute() method, It executes when our controller is called.  Execute action based on request and return the result with the controller class.

Now our final URL will look like this, training/index/training

Creating a layout and template files for our module to render content on the browser.

Layout Structure: <frontName>_<controllerFolderName>_<controllerClass>

The layout XML file name will be our action path with the underscore(_) symbol.  Here Layout file will be a training_index_training.xml file.

Path: app/code/Rbj/Training/view/frontend/layout folder with the following code:

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Rbj\Training\Block\Index\Training" name="index.training" template="Rbj_Training::index/training.phtml"/>
        </referenceContainer>
    </body>
</page>

In the above XML file, the Block class is Rbj\Training\Block\Index\Training, We need to define Block for keeping our templates dynamic function. We will create a block further in this tutorial.

Create template file training. phtml for our module representation in the frontend,
app/code/Rbj/Training/view/frontend/templates/index/training.phtml,

<?php

/** @var $block \Rbj\Training\Block\Index\Training */
echo $block->getTextMessage();
?>

<h2>Hello First Magento 2 Basic module.</h2>

Create Training.php block class for a dynamic function which is required to call in our template file.
The file path, app/code/Rbj/Training/Block/Index/Training.php

<?php
declare(strict_types=1);

namespace Rbj\Training\Block\Index;

use Magento\Framework\View\Element\Template;

class Training extends Template
{
    public function getTextMessage(): string
    {
        return 'Greetings!!! Magento 2 Module completed.';
    }
}

Now When you hit the URL, {{Site_Base_Url}}/training/index/training,
You will redirect to the 404 pages because our module is not installed yet.

To install a module in Magento 2,  We need to run the command using SSH, log in with SSH, and go to your project root path where Magento is installed,
Run the given command,

php Magento setup:upgrade
php Magento setup:static-content:deploy -f
php Magento cache:flush

Now You run the URL in the front end,
{{Site_Base_Url}}/training/index/training
You have a display message which you have typed in the template file.

The result is,

Create a simple Hello World module in Magento 2

Using the above steps, You can create your own Custom Module in Magento 2 with easy steps.