Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Magento 2 Hello World Module

Magento 2 is a modular system. This means all functionalities or business logic is designed and developed as Modules. Every Module can work pretty much as a standalone unit or with minimum dependencies with other modules. These are the structural elements ofMmagento 2. 

A Module is a package that pretty much encapsulates a single responsibility or a set of logical sequences of responsibilities. This follows separation of concerns (SoC) design principle. Magento 2 is shipped with a core set of modules, which we can extend depending on the customization that needs to be implemented.

For a newbie, the steps to create a simple module can be quite overwhelming. This is due to the many steps involved to get the module up and running. This modular approach will make application development & customization quite easy once you understand the steps. . 

Any standard text editor can be used for the development. However, community recommendations are as follows : PHPStorm (Paid), Apache NetBeans (Free), Visual Studio Code (Free)

Once we set up the dev box, it looks pretty much as below. Here I am using Apache NetBeans. We write our custom modules under the code directory. ( I have created the code directory under app Folder in this case)

All the Magento 2 core modules are located under vendor/magento. A standard module folder structure looks as below.

This is the folder structure of the Magento catalog module. All the modules start with a registration.php file and a module.xml file under etc folder. This is the bare minimum requirement for a module. Cron folder contains logic for a scheduler. Observer container the logic to work as publish subscribe pattern. i18n is specifically for language specific.

Steps to create a module

In Magento 2, we can create modules under the app/code folder. Inside the code folder, we need to create a folder for the vendor name. Under the vendor folder, we need to create a folder with  the module name. In this example, I am using HelloVendor and HelloModule as vendor and module names respectively. Inside the module folder, we need to create two files. One is registration.php file (at the module root folder) and module.xml file under etc folder. registration.php file code is as follows:

    \Magento\Framework\Component\ComponentRegistrar::register(

\Magento\Framework\Component\ComponentRegistrar::MODULE,

‘HelloVendor_HelloModule’,

__DIR__

);

This is pretty much a standard registration file code with the module name as the only change. (_. Create a module.xml file under etc (small letter)  folder. The sole purpose of this file is to declare the module, its version and dependencies. For HelloModule module we have no dependencies.

        xsi:noNamespaceSchemaLocation=”urn:magento:framework:Module/etc/module.xsd”>

Current folder structure looks like this:


To install the module with magento we can run the below command in the Magento root folder.

C:\xampp\htdocs\m2>php bin/magento setup:upgrade

We can also see the module registration in  app/etc folder config.xml file. Value 1 means the module is successfully registered 

We will create a simple UI to display a Hello World in the browser.  For this, we need to add a Controller class. The controller class resides in Controller directory of the module. Its functionality is to receive the request, process and render the page. There are 2 types of controllers – frontend controller and backend controller. 

In this article we focus on the frontend controller. Every controller class should inherit from \Magento\Framework\App\Action\Action core class and implement execute() method.  This method will execute when the user hits the url.

Create a folder by name Controller (C is capital and the name is case sensitive)  under the module folder. Create another folder, say View, under Controller folder and add controller file/action file by name HelloWorld.php

Dependency Injection (DI) is the way to retrieve objects in Magento 2.  In this process the class receives the object it depends as a constructor argument. In our case, we pass Context and PageFactory class as the arguments. PageFactory is responsible for creating a page.

namespace HelloVendor\HelloModule\Controller\View;

class HelloWorld extends \Magento\Framework\App\Action\Action {

    protected  $pageFactory;

    public function __construct(

               \Magento\Framework\View\Result\PageFactory $pageFactory,

               \Magento\Framework\App\Action\Context $context) {

        $this->pageFactory = $pageFactory;

        parent::__construct($context);

    }

    public function execute() {

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

    }

}

This looks as below in the Editor

We need to add routing configuration for the frontend area. This can be done by adding route.xml file in etc/frontend folder.  Route files contain router id as standard, which is fixed for the frontend router, a route id, which should be unique, a frontname that is unique, which is going to be the part of the url and module detail.

        xsi:noNamespaceSchemaLocation=”urn:magento:framework:App/etc/routes.xsd”>

    

        

            

        

    

Now we create a view layer for the module. View consists of blocks, templates and layouts. We need to next create layout xml file for our module. This file dictates the structure of the page. Layout file contains the block details, template details and a unique name. The layout xml file is created under the  view/frontend/layout folder at the root module folder. This is named as hellomodule_view_helloworld.xml.

      xsi:noNamespaceSchemaLocation=”urn:magento:framework:View/Layout/etc/page_configuration.xsd”>

    

        

            

                   name=”hellovendor_helloworld”  

                   template=”blockcontent.phtml”/>

        

        

 

Next step, we need to create the Block class. Block class provides data to the template to display. In real-time scenario, block instantiates model classes,  which then can query databases. Every block class extends Magento\Framework\View\Element\Template core class. Block will render the HTML by using the template file we assigned in the layout.xml file .

namespace HelloVendor\HelloModule\Block;

use Magento\Framework\View\Element\Template;

class Hello extends Template

{

   public function _prepareLayout() {

   }

}

Create blockcontent.phtml template file under view/templates folder. This is just to display Hello World

Hello World!

Final output looks like this –


The completed code folder structure is as shown below:

Congratulations, we have successfully created the HelloWorld module.

Read more: Definite reasons to migrate to Magento 2

Author Bio 

Gigy Joseph works with Suyati as a Principal Architect. He has multifaceted experience on different domains & technology stack. His current focus is on the Microsoft cloud technologies and process improvements.




The post Magento 2 Hello World Module appeared first on Suyati Technologies.



This post first appeared on Http://suyati.com/blog/, please read the originial post: here

Share the post

Magento 2 Hello World Module

×

Subscribe to Http://suyati.com/blog/

Get updates delivered right to your inbox!

Thank you for your subscription

×