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

Welcome to Kishan Savaliya's Magento 2 Blog. Are you new in Magento 2? If Yes, then you're in right place to learn Magento 2 from scratch. I will try my best to provide step by step guidance in my every post, so you can learn Magento 2 easily. Save my website in your bookmarks. ;-)

In this post, I will show you how to create your first simple Hello World module in Magento 2. It's quite easy, you just need to take care of files and directory structures. If you're new developer in Magento 2 technology and you wants to explore Magento 2 in depth then you must know how to create simple module first. So let's start..

First of all, Go to you Magento 2 Root directory, there you can see multiple directories and files available.

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

Now, navigate inside your app/code directory, if you don't see any code name directory inside app then generate new directory and navigate inside it.

Then you need to create Package name/ Vendor name directory there. So I will create SK as my Vendor directory, you can choose any vendor name and you can create that named directory, and navigate inside it.

Create Module name directory inside Vendor name directory, So I will create SimpleModule as my Module directory, here also you can choose whatever named directory, and navigate inside that directory.

So, SK_SimpleModule is our module name.

Now, in Magento 2, you must have to create 2 files registration.php and module.xml file, these both files are required for the module to exist.

registration.php : This file is useful to register new module, which tells Magento how to locate module.

module.xml : This file contains Module name, version and Dependencies of module. So in our case, module name will be SK_SimpleModule. Module's version indicates the current version of the database schema and data, and Dependencies means if our custom module depends on any other module then we can define that here in module.xml with <sequence></sequence> tags.

So let's create registration.php file in your module directory here

app/code/SK/SimpleModule/registration.php

Content for this file is..

<?php
/**
 * SK Simple Magento 2 module for beginner.
 */
use \Magento\Framework\Component\ComponentRegistrar as ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'SK_SimpleModule', __DIR__);

Create module.xml file here

app/code/SK/SimpleModule/etc/module.xml

Content for this file is..

<?xml version="1.0"?>
<!--
/**
 * SK Simple Magento 2 module for beginner.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="SK_SimpleModule" setup_version="1.0.0" />
</config>

Above both files are required to register new module. So let's register new module in your Magento. You have to run below command to enable and register new module.

php bin/magento module:enable SK_SimpleModule

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

You can see our new module is enabled now successfully with Magento, and it's showing message "To make sure that the enabled modules are properly registered, run 'setup:upgrade'." So we will run below command to register this module.

php bin/magento setup:upgrade

Now our module is successfully registered. Now we will create Route for frontend, this can be used to assign a URL to a corresponding controller and action. We can create router for frontend as well as backend. So for now we will create router for frontend.

Create routes.xml file

app/code/SK/SimpleModule/etc/frontend/routes.xml

Content for this file is..

<?xml version="1.0"?>
<!--
/**
 * SK Simple Magento 2 module for beginner.
 *
 * @package SK_SimpleModule
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="simplemodule" frontName="simplemodule">
            <module name="SK_SimpleModule" />
        </route>
    </router>
</config>

Here in this file, frontName attribute of router tag is our first part of our custom URL.

Magento's default URL structure is : <your-base-url>/<frontName>/<controllerDirectoryName>/<actionFileClassName>. So basically, it'll be http://example.com/simplemodule/hello/world. Here Hello is our Controller directory name and World is Action name that we will use in below steps.

Now, create Controller directory Hello and Action class file World.php here

app/code/SK/SimpleModule/Controller/Hello/World.php

Content for this file is..

<?php
/**
 * SK Simple Magento 2 module for beginner.
 *
 * @package SK_SimpleModule
 */

namespace SK\SimpleModule\Controller\Hello;

class World extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ){
        $this->resultPageFactory = $resultPageFactory;
        return parent::__construct($context);
    }
     
    public function execute()
    {
        $resultPageFactory = $this->resultPageFactory->create();
        $resultPageFactory->getConfig()->getTitle()->set(__('SK Simple Magento 2 Hello World module')); //You can set your page's title here.
        return $this->resultPageFactory->create();
    } 
}
  • We have added 'Magento\Framework\View\Result\PageFactory' into Controller's constructor which is used further to initialize the layout in execute() method. So let's create layout XML file.

In Magento 2, layouts are used to describe basic structure of any web page. We can use Containers and Blocks to create proper layout. Containers are used to create page layout. We can use multiple blocks and containers inside any container. Blocks are designed for outputting HTML content of the page and that contains their template files.

Now we will create new layout file for our action. We are creating layout for frontend so all frontend layout files of modules located inside this directory..

app/code/SK/SimpleModule/view/frontend/layout/

For different actions, we can create seperate layout XML files and can render HTML content. We can follow this structure to create any new XML file for any action <router-name>_<controller-directory-name>_<action-class-name>.xml.

Let's create layout XML file here

app/code/SK/SimpleModule/view/frontend/layout/simplemodule_hello_world.xml

Content for this file is..

<?xml version="1.0"?>
<!--
/**
 * SK Simple Magento 2 module for beginner.
 *
 * @package SK_SimpleModule
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">       
    <referenceContainer name="content">
        <block
            template="SK_SimpleModule::helloworld.phtml"
            class="SK\SimpleModule\Block\HelloWorld"
            name="helloworld-block"/>
    </referenceContainer>
</page>
  • We used block and template in above XML file. So what is Block and templates in Magento 2 ?

Blocks and templates in Magento 2

  • The Block file should contain all the view logic required, it should not contain any kind of html or css. Block file are supposed to have all application view logic.
  • So we will create Block file in our module. For that we need to create Block directory in our module.
  • Inside Block directory create HelloWorld.php
app/code/SK/SimpleModule/Block/HelloWorld.php

Content for this file is..

<?php
/**
 * SK Simple Magento 2 module for beginner.
 *
 * @package SK_SimpleModule
 */

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

    protected function _prepareLayout()
    {
        $this->setValue("Hello World from setValue() function in _prepareLayout()");
    }

    public function getContent(){
        $content = "Hello, How are you? - using getContent() function.";
        return $content;
    }
}
  • Afer creating above block file we need to create one template file. We can create module's template file on this location for frontend.
app/code/SK/SimpleModule/view/frontend/templates/helloworld.phtml

Content for this file is..

<?php
/**
 * SK Simple Magento 2 module for beginner.
 *
 * @package SK_SimpleModule
 * @var \SK\SimpleModule\Block\HelloWorld $block
 */
?>
<strong><?php echo __("Hello World..!"); ?></strong><br>
<i><?php echo $block->getValue(); ?></i><br>
<?php echo $block->getContent(); ?>
  • We are using phtml files for Magento template file, we can use HTML and PHP code togather here.
  • We can add HTML as well as small view logics in template files in Magento.

So finally, our file and directory structure for this module is..

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

Now only few steps remaining to check output of hello world module. So let's do that, you have to regenerate code. So you need to run below command once.

php bin/magento setup:di:compile
php bin/magento cache:clean && php bin/magento cache:flush

Now simply, you can run this URL in your browser to check output : <your-base-url>/simplemodule/hello/world. and you can see output.

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

You can create simple module in Magento 2 easily if you'll follow above steps properly.

Hope you may like this article and can understand this easily. You can add comments below in case if you have any questions regarding this article or if I missed anything here. I will check and get back to you with proper solution.

If you enjoyed this blog post, share it with friends!