How to create Hello World module in magento2?

Table of Contents

Introduction

Creating a “Hello World” module in Magento2 is a great way to learn the basics of Magento2 and get familiar with the development environment. The purpose of this tutorial is to provide a step-by-step guide on how to create a simple “Hello World” module in Magento2, and explain the various components of the module.

Creating the Module Structure

The first step in creating a “Hello World” module in Magento2 is to create the module structure. Magento2 follows a certain convention for module structure. The module must be located under the “app/code/” directory and named after the vendor. For this tutorial, the vendor name is “Tutorial” and the module name is “HelloWorld”.

The “app/code/Tutorial/HelloWorld” directory should contain the following files and directories:

  1. etc/module.xml
  2. registration.php
  3. composer.json
  4. Controller
  5. Block

The “etc/module.xml” file contains the information about the module, such as its name, version, dependencies, and so on. The ?registration.php? file registers the module with Magento2. The “composer.json” file contains the necessary information for the module to be installed using Composer.

The “Controller” directory contains the files related to the module’s controller, such as the action classes and the router file. The “Block” directory contains the files related to the module’s block, such as the layout files.

Creating the Module Configuration

The “etc/module.xml” file contains the information about the module, such as its name, version, dependencies, and so on. The following is an example of a “etc/module.xml” file for the “Hello World” module:

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Tutorial_HelloWorld" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Backend"/>
        </sequence>
    </module>
</config>

The “name” attribute is the name of the module. The “setup_version” attribute is the version of the module. The “sequence” element contains the modules that need to be loaded before this module is loaded. In this example, the “Magento_Backend” module needs to be loaded before this module is loaded.

Creating the registration.php File

The “registration.php” file registers the module with Magento2. The following is an example of a “registration.php” file for the “Hello World” module:

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

This file is very simple and does not contain any code. It simply registers the module with Magento2.

Creating the composer.json File

The “composer.json” file contains the necessary information for the module to be installed using Composer. The following is an example of a “composer.json” file for the “Hello World” module:

{
    "name": "tutorial/helloworld",
    "description": "Tutorial Hello World Module",
    "type": "magento2-module",
    "version": "1.0.0",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0",
        "magento/module-backend": "100.0.0"
    },
    "autoload": {
        "files": ["registration.php"],
        "psr-4": {
            "Tutorial\\HelloWorld\\": ""
        }
    }
}

The “name” attribute is the name of the module. The “description” attribute is a description of the module. The “type” attribute indicates the type of package. The “version” attribute is the version of the module. The “require” section contains the dependencies for the module. The “autoload” section contains the files and directories that need to be autoloaded.

Creating the Controller

The “Controller” directory contains the files related to the module’s controller, such as the action classes and the router file.

The first step is to create the router file. The router file is responsible for mapping the request URLs to the appropriate action classes. The following is an example of a router file for the “Hello World” module:

<?php

namespace Tutorial\HelloWorld\Controller;

use Magento\Framework\App\RouterInterface;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ResponseInterface;

class Router implements RouterInterface
{
    /**
     * @var ActionFactory
     */
    protected $actionFactory;

    /**
     * Response
     *
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @param ActionFactory     $actionFactory
     * @param ResponseInterface $response
     */
    public function __construct(
        ActionFactory $actionFactory,
        ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->response = $response;
    }

    /**
     * Validate and Match
     *
     * @param \Magento\Framework\App\RequestInterface $request
     * @return bool
     */
    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $identifier = trim($request->getPathInfo(), '/');
        if (strpos($identifier, 'helloworld') !== false) {
            $request->setModuleName('helloworld')->setControllerName('index')->setActionName('index');
            $request->setAlias(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $identifier);
            return $this->actionFactory->create('Magento\Framework\App\Action\Forward');
        }
        return null;
    }
}

This router file is responsible for mapping the request URL “/helloworld” to the “index” action of the “index” controller.

The next step is to create the controller file. The following is an example of a controller file for the “Hello World” module:

<?php

namespace Tutorial\HelloWorld\Controller\Index;

use Magento\Framework\App\Action\Context;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory resultPageFactory
     */
    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {
        $this->getResponse()->setBody("Hello World!");
    }
}

This controller file is responsible for displaying the “Hello World!” message when the “/helloworld” URL is accessed.

Creating the Block

The “Block” directory contains the files related to the module’s block, such as the layout files. The following is an example of a layout file for the “Hello World” module:

<page 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="Tutorial\HelloWorld\Block\HelloWorld" name="helloworld" template="Tutorial_HelloWorld::helloworld.phtml"/>
        </referenceContainer>
    </body>
</page>

This layout file is responsible for displaying the “Hello World!” message when the “/helloworld” URL is accessed.

The next step is to create the block file. The following is an example of a block file for the “Hello World” module:

<?php

namespace Tutorial\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context
    ) {
        parent::__construct($context);
    }

    public function getHelloWorldMessage()
    {
        return "Hello World!";
    }
}

This block file is responsible for displaying the “Hello World!” message when the “/helloworld” URL is accessed.

Conclusion

In this tutorial, we have learned how to create a simple “Hello World” module in Magento2. We have also discussed the various components of the module, such as the module structure, configuration, controller, and block. By following the steps outlined in this tutorial, you should be able to easily create a “Hello World” module in Magento2.