Magento2

How to create a Helloworld module in Magento2?

How to create a Helloworld module in Magento 2?

So In this blog We will discuss the topic of how to create a Hello World module in Magento 2. In order to help you have the clearest and easiest way to create the hello world module. At the end of blog the module’s output will say “Hello world!” in the block content on a custom frontend route.

Follow the below steps to create HELLO WORLD module.

All of our custom modules in Magento 2 go under the app/code directory. And the modules have a 2 part naming structure, i.e, MerchantName/VendorModuleName. This is so that the modules can be organised more efficiently. So, assuming our MerchantName is V4U and our first VendorModuleName will be called Helloworld, the directory structure for our module is app/code/V4U/Helloworld/.

A Magento 2 module is found in app/code/MerchantName/ModuleName/. So basically Magento 2 for any module/extension there are mainly three required/mandatory files :

  • registration.php : Both Composer and Magento use this file. Composer to determine which files to autoload (loading automatically based on their namespace path).
  • composer.json : Depending on how the module will be installed, this may or may not be necessary. I always include it in my modules as this will likely be required in the future. Because It tells Composer about requirements and paths.
  • etc/module.xml : This file will likely become deprecated in favour of composer.json. So In this file, we specify the module’s name (which must match the name specified in registration.php). You also specify any modules on which this module depends with the sequence element.

Note : So our module will mostly work without a composer.json file at this time. However, It will run into an error when try to use the Magento CLI to uninstall a module.

And GitHub Repository of the Module: https://github.com/vrajeshpatel4u/v4u-helloworld

Here is the step-by-step guide on creating Magento 2 module/extension.

So I have set the module’s MerchantName(Namespace) as V4U and VendorModuleName (module’s name) as Helloworld. So, our module is V4U_Helloworld.

(01) Register your Module : You have to register your module in your Magento 2. This is done through Magento ComponentRegistrar class. You should create a new file named registration.php in your module’s directory.

app/code/V4U/Helloworld/registration.php

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

(02) Create composer.json file :

app/code/V4U/Helloworld/composer.json

{
    "name": "v4u/helloworld",
    "description": "Simple Hello World Module for Magento 2",
    "type": "magento2-module",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "authors": [
        {
            "email": "[email protected]",
            "name": "Vrajesh Patel"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "V4U\\Helloworld\\": ""
        }
    }
}

(03) Create Module’s Configuration File :

app/code/V4U/Helloworld/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="V4U_Helloworld" setup_version="0.0.1" />
</config>

(04) Create Module’s Frontend Router File :

app/code/V4U/Helloworld/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="helloworld" frontName="helloworld">
            <module name="V4U_Helloworld"/>
        </route>
    </router>
</config>

(05) Create Controller Class : In Magento 2, we should create a separate controller class for each action because each controller class will only have one method named execute().

app/code/V4U/Helloworld/Controller/Index/Index.php

<?php

namespace V4U\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;


class Index extends Action
{
    /**
     * The PageFactory to render with.
     *
     * @var PageFactory
     */
    protected $_resultsPageFactory;

    /**
     * Set the Context and Result Page Factory from DI.
     * @param Context     $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->_resultsPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Show the Hello World Index Page.
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute() {
        return $this->_resultsPageFactory->create();
    }
}

(06) Create Block Class :

app/code/V4U/Helloworld/Block/HelloWorld.php

<?php
namespace V4U\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        array $data = []
    )
    {        
        parent::__construct($context, $data);
    }
    
    public function getHelloWorld()
    {
        return 'Hello World';
    }
    
}
?>

(07) Create Design Layout File :

app/code/V4U/Helloworld/view/frontend/layout/helloworld_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>
            V4U Simple Magento 2 Module
        </title>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="V4U\Helloworld\Block\HelloWorld" name="helloworld" template="V4U_Helloworld::helloworld.phtml" />
            <!--<block class="Magento\Framework\View\Element\Template" template="V4U_Helloworld::helloworld.phtml"/>-->            
        </referenceContainer>
    </body>
</page>

(08) Create Design Template File :

app/code/V4U/Helloworld/view/frontend/templates/helloworld.phtml

<h2>
    <?php echo $block->getHelloWorld(); ?>
</h2>

(09) Run the below commands to enable and register the module :

php bin/magento module:enable V4U_Helloworld

php bin/magento setup:upgrade

If It doesn’t work, then you can try using sudo at the beginning of the command.

sudo php bin/magento setup:upgrade

php bin/magento cache:clean

php bin/magento cache:flush

To check the enabled/disabled status of all cache types, you can run the following command:

php bin/magento cache:status

Now check result. So in our example, the final URL will look like this:

http://localhost/magento234/helloworld/index/index

🙂 Happy Coding. Keep Liking & Sharing 💻

DevDocs

So Home
Tagged , , , ,