how to create a hello world module in magento-2

In Today’s tutorial we will see how to create a hello world module in Magento-2. We will print hello world on the screen.

The objective of today’s tutorial is to understand the module structure of Magento-2 and we will show a hello world text on screen.

First of all we will have to follow these steps:

  1. Disable Magento Cache:

    Magento 2 has implemented cache in very awesome way which results into quick page load and fast speed . Whenever we will make any change in code , it will not be reflected on site because Magento’s Caching system will be loading it from cache so we will have to flush the cache every time which results into wasting of time. To save our time we will disable the cache. To disable cache go to Admin → System → Cache Management → select all cache types and disable them.

  2. Enable Developer Mode:

    By default Magento runs in default mode , and we need to make it run into developer mode. Why developer mode ? because enabling developer mode will show all the errors . Run below command to enable developer mode.

    php bin/magento deploy:mode:set developer

    If you are using xampp on your localthen run this command 

    /opt/lampp/bin/php bin/magento deploy:mode:set developer

Magento-2 Module Structure

For those who are familiar with Magento-1 , module structure of Magento-2 is bit different. In Magento 1 our code used to split in various folders and creating an install-able package was a tough job , but in Magento-2 code of one module resides inside one folder and can be easily used to create install-able package.

Directory Structure of Magento Module:

app/code/<namespace>/<module_name>

<namespace> which may also be called as vendor_name is the name of folder which contains module. A namespace may have any number of modules. For this tutorial we will be using Mega as namespace or say vendor_name

<module_name>  is the name of module which we are building. Always chose a name for module which reflects the module functionality. It is considered as best practice. We will be using HelloWorld as module name

So detailed directory structure will be:

Mega/HelloWorld/

Block : This folder contains the block files

Controller: This folder contains the Controller Files

Helper : This folder contains the helper Files

Model: This folder contains the Model Files

Observer:  This folder contains the Observer Files which are used to hook any event. In Magento 2 we use di.xml for hooking events. Event System is not in the scope of this post. We will discuss event system in near future posts.

Setup: This setup folder is equivalent to Magento-1’s sql folder. This folder holds the installData and InstallSchema file ffor manipulating the database. With the help of these files we can create , alter table and other operations at Database level

etc : This folder contains the configuration for front-end as well as admin area.

view: This folder has 2 sub folders. adminhtml and frontend. These folders contains the layout , template files as well as javascript and css files.

Creating Hello World Module in Magento-2

We will be creating these files for creating a hello world module. For fresh Magento-2 installation you notice that there is no code folder , you may create it manually.

  1.  app/code/Mega/HelloWorld/etc/module.xml file
  2.  app/code/Mega/HelloWorld/registration.php
  3. app/code/Mega/HelloWorld/etc/frontend/routes.xml
  4. app/code/Mega/HelloWorld/Controller/Index/Index.php
  5. app/code/Mega/HelloWorld/Block/Hello.php
  6. app/code/Mega/HelloWorld/view/frontend/layout/helloworld_index_index.xml
  7. app/code/Mega/HelloWorld/view/frontend/templates/hello.phtml

 

Creating app/code/Mega/HelloWorld/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="Mega_HelloWorld" setup_version="1.0.0">
    </module>
</config>

In above code , setup_version is the setup version of the module. This version is checked when we want to create a table or we want to do some database level operations.

Registering the module

To register a module we will create a registration.php file with below contents:

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

After performing above steps our module is created and registered in Magento. Now we will confirm that our module is registered. By default when we create a module , it is disabled. So we have to enabled the module too.

Open terminal and change directory to your magento root and run this command

php bin/magento module:status

This command will show some output and last of the output will look like this

List of disabled modules: Mega_HelloWorld

now we will enable the module by running this command

php bin/magento module:enable Mega_HelloWorld

Now if we check file app/etc/config.php we will find this

'Mega_HelloWorld' => 1 This confirms that our module is now enabled and registered. After this we will define a route for our module. In this we will define a frontname of the module. In Magento url is comprises of module frontname , controller name and action name. Now we will register frontname for our module. Create routes.xml in app/code/local/Mega/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="Mega_HelloWorld" />
        </route>
    </router>
</config>
Now we will create index controller and index action
create a folder inside Controller folder . Name the folder Index and create a file index.php in it

Add below code in file

<?php
namespace Mega\HelloWorld\Controller\Index;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
 
    public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }
} Now Let's create a block file that will provide the hello world text to our template file that will print the text screen. Create a file Hello.php in Block folder in module and add the below contents
<?php
namespace Mega\HelloWorld\Block;
 
class Hello extends \Magento\Framework\View\Element\Template
{
    public function getTextToPrint()
    {
        return 'Hello world!';
    }
}

Now we will create a layout file to include our block and template for our module for url of index controller and index action. In Magento-2 this is done a bit differently than magento-1. in Magento-2 for every controller action we create a separate layout file. we will create file hellowold_index_index.xml in view/frontend/layout folder and add the below contents
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
    <body>
        <referenceContainer name="content">
            <block class="Mega\HelloWorld\Block\Hello" name="megahelloworld" template="hello.phtml" />
        </referenceContainer>
    </body>
</page>

Now we will create a template file hello.phtml in view/frontend/templates folder. We will add the below content
<p><?php echo $this->getTextToPrint(); ?></p>


We are done with all sort of codes and now if we open the below url /helloworld/index/index
we will see a hello world text printed on screen. That’s all for today’s post. If you face any issue or you have any doubt feel free to post it in comments and we will help you out. If you need any service or you are looking for customization in your magento store feel free to drop us a line using the form on http://www.codeinnovers.com/contact-us

Add a Comment

Your email address will not be published. Required fields are marked *