Are you just starting out to learn Magento 2? Then creating a Simple Hello World Module will be very helpful!

This simple Module that displays “Hello World” in the browser can help you learn some of the basics of Magento 2 and help you through as a beginner level Magento Developer.

Creating Entry Point Files

Firstly, create two entry point files - registration.php and module.xml - to define the Custom Module.

  • registration.php — It is used to Register New Module In Magento 2 System.
  • module.xml — the XML file defines the module name. It also contains a <sequence> tag for the Dependency of Other modules in the module.

You will find the module simply residing in the app/code folder of the Magento instance.

To create a module, you need to complete the following steps:

  1. Create Directory under the app/code
  2. Create the etc/module.xml and registration.php file
  3. Create routes.xml and Controller file
  4. Creating template files & a layout for our module
  5. Installing our module in Magento 2
  6. Running the module

Let’s go through each of these steps in detail.

 

Step 1: Create Directory under the app/code

You can keep any name for Vendor name and Module name. For example, in this demo we have kept Vendor name MageSpark & Module name as HelloWorld

 

Step 2: Create the etc/module. xml and registration.php file

Next, start creating the basic module.

Create a registration.php file, it is used to register your module.

The following is the Full Path - app/code/MageSpark/HelloWorld/registration.php

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

Now, simply Create module.xml file, this is the path:

app/code/MageSpark/HelloWorld/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="MageSpark_HelloWorld" setup_version="1.0.0"/>
</config>

In the above code, keep the naming convention equal to the (VendorName_ModuleName) you used.

 

Step 3: Create routes.xml and Controller file

Next, create routes.xml file, here’s the path: app/code/MageSpark/HelloWorld/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 id="helloworld" frontName="helloworld"> <module name="MageSpark_HelloWorld" /> </route> </router> </config>

The frontName attribute in the code above represents the first part of the custom URL

The default URL structure for Magento 2 is as follow, <frontName>/<areaControllerDirectoryPath>/<controllerClass>

Where areaControllerDirectoryPath is the Directory Path of your area controller.

Where an area might be either front or admin area but in our case, <areaControllerDirectoryPath> equals Index and <controllerClass> equals Helloworld for the demo Module.

Create <controllerClass>, the path is: app/code/MageSpark/HelloWorld/Controller/Index/Helloworld.php

<?php

namespace MageSpark\HelloWorld\Controller\Index;

/**
 * Class Helloworld
 *
 * @package MageSpark\HelloWorld\Controller\Index
 */
class Helloworld extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $pageFactory;

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

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $pageFactory = $this->pageFactory->create();
        // Add page title
        $pageFactory ->getConfig()->getTitle()->set(__('Hello World Module'));

        return $this->pageFactory->create();
    }
}

In Magento 2 controllers have only one method (execute()) that will be called by front controller. It means when our controller is caller, it will execute.

Lastly, our URL will finally look like this, helloworld/index/helloworld

 

Step 4: Creating template files & a layout for our module.

First, you need to create a helloworld_index_helloworld.xml file in the app/code/MageSpark/HelloWorld/view/frontend/layout directory. Use the following code in it:

<?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="MageSpark\HelloWorld\Block\Index\Helloworld" name="helloworld"
                template="MageSpark_HelloWorld::index/helloworld.phtml"/>
	</referenceContainer>
    </body>
</page>

In the above code, the Block class is MageSpark\HelloWorld\Block\Index\Helloworld.

To keep our templates dynamic function, we need to define Block, and further in this step-by-step tutorial, we will create a Block to help you understand it better.

Create a template file helloworld.phtml for our module representation in the frontend, this is the path: app/code/MageSpark/HelloWorld/view/frontend/templates/index/helloworld.phtml

<?php

/** @var $block \MageSpark\HelloWorld\Block\Index\Helloworld */
?>
<h2><?= $block->getHelloWorldMessage(); ?></h2>

Now, create a Helloworld.php block class for a dynamic function that is needed to call in our template file.

The file path is - app/code/MageSpark/HelloWorld/Block/Index/Helloworld.php

<?php

namespace MageSpark\HelloWorld\\Block\Index;

/**
 * Class Helloworld 
 *
 * @package MageSpark\HelloWorld\\Block\Index;
 */
class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    /**
     * @return string
     */
    public function getHelloWorldMessage()
    {
        return 'Hello World!';
    }
}

Now, when you open the URL - {{Site_Base_Url}}/helloworld/index/helloworld,

you will get redirected to 404 page because our Hello World module is not installed yet.

Step 5: Installing our module in Magento 2

To install our module in Magento 2, you need to use SSH to run the command. Login with SSH & navigate to your project root direcotory where Magento is installed.

Finally, run the below given command:

php bin/magento module:enable MageSpark_HelloWorld
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f

 

Step 6: Running the module

After Step 5, simply run the URL - {{Site_Base_Url}}/helloworld/index/helloworld- in the frontend.

And, voila! You get a display message that you typed in the template file.

This is what it should look like,

Create A Simple Hello World Module In Magento 2

Conclusion

Use the above steps, modify it a bit and start creating your own Custom Module in Magento 2.