Magento2 is the latest version of a very popular e-Commerce platform. It is estimated that one in four eCommerce businesses today are using Magento software. Magento provides flexibility and adaptability with the changing customer needs to customize our platform in order to create a unique layout and brand experiences.

What is a module?

A module can be easily defined as a directory in Magento that contains helpers, models, controllers, blocks etc, which are expected to perform a particular task. Modules will go in app/code directory in Magento2.

app/code/<VendorName>/<ModuleName>

Before proceeding to development, lets make sure that few things are done in Magento2.

Disabling Magento2 cache :- Disabling cache can save us some time, as we don’t need to manually flush cache each and every time we’ve made some changes. To disable cache, we can go to Admin > System > Cache Management > Select all cache types and disable them.

Developer mode :- We can put Magento in developer mode, so that we can see all the errors and warnings Magento throws during development. To put magento in developer mode, we can go to Magento2 root in our terminal and run this command.

php bin/magento deploy:mode:set developer

Now lets go on and see the steps involved in the Module development process in Magento2.

A directory for our module

First we should create a directory for our module files. It should be like app/code/<VendorName>/<ModuleName> in our Magento2 directory. Lets use Met as our vendor name and Mymodule as our module name. So our folder structure will be like app/code/Met/Mymodule. We can create an app/code folder if it doesn’t already exists.

Configuration file for our module

The etc directory is where a module has its configuration file, and thats where Magento2 is gonna look for those informations. So lets create the folder etc and put module.xml file in app/code/Met/Mymodule/etc. The file content is,

<?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="Met_Mymodule" setup_version="1.0.0" />
</config>

Here, we’ve configured a module with Met_Mymodule name with version 1.0.0.

Registering the module

All modules in Magento system must be registered through the magento ComponentRegistrar class. The file we need is registration.php  and it will go in our Magento2 root. So lets create our file  registration.php in app/code/Met/Mymodule. The file content is,

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

As of now, we’ve created an empty module. Lets check whether Magento2 has recognized our module or not by executing the following command from Magento2 root.

php bin/magento module:status

If we see our module name under disabled modules list, lets understand that Magento has recognized our module but its disabled. To enable our module lets execute another command,

php bin/magento module:enable Met_Mymodule

Now our module is enabled. To make sure of it lets go to  Admin → Stores → Configuration → Advanced → Advanced and see our module is present in the list.

As we’ve enabled our module we need to check and upgrade our module database by executing this command,

php bin/magento setup:upgrade

Routing our module

A router assigns our module to its corresponding controller and action. Magento2 follows the following Url format,

http://example.com/<front_name>/<controller_name>/<action_name>

In the above URL we see front_name which will be defined in our routes.xml file. So lets create routes.xml in app/code/Met/Mymodule/etc/frontend.

The content for our routes.xml is,

<?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="mymodule" frontName="mymodule">
            <module name="Met_Mymodule" />
        </route>
    </router>
</config>

Route id identifies the route node uniquely in the Magento system, and the frontName defines the first segment of your URL.

Now the URL for our module is http://example.com/mymodule/.

The front name in our url has to be unique.

Creating controller and action for our module

Now lets create a controller for our module to receive requests, process it and render a page. Our module controller can have more than one files, which can contain actions with the execute() method. First lets select a url for our action, like http://example.com/mymodule/index/display.
In the above url mymodule is our front name, index is the name of our controller folder and display is our action name.
So now we need to create our action file which is Display.php. Lets create it in

app/code/Met /Mymodule/Controller/Index

The content for our action file is,

<?php
namespace Met\Mymodule\Controller\Index;
use Magento\Framework\App\Action\Context;
class Display 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;
    }
}
?>

The method execute() in our action file will be invoked when the action page is called.

Creating a Block for our module

All logic for our view can be placed inside our Block file. It will not have any html or css. Lets create a simple block class in our Block file with a method that outputs a string.

So lets create Mymodule.php in app/code/Met/Mymodule/Block folder.

The content for our block file is

<?php
namespace Met\Mymodule\Block;

class Mymodule extends \Magento\Framework\View\Element\Template
{
    public function getMyModuleTxt()
    {
        return 'This is a sample plugin!';
    }
}
?>

Magento2 block are extended from \Magento\Framework\View\Element\Template. Here we have a method getMyModuleTxt() which we will call from our template file.

Creating layout and template files for our module

Our layout file will be an xml file which defines our page structure, and we put it in app/code/Met/Mymodule/view/frontend/layout. Our layout file will have its name in the format {routerId}_{controllerName}_{actionName}.xml.

So our layout file will be mymodule_index_display.xml in app/code/Met/Mymodule/view/frontend/layout and its content will be,

<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="Met\Mymodule\Block\Mymodule" name="mymodule" template="mymodule.phtml" />
        </referenceContainer>
    </body>
</page>

mymodule_index_display.xml is the layout handle for our controller. In our layout file we have added our block in the content container and set the template of our block to mymodule.phtml, which we create in the next step.

Lets now create a mymodule.phtml file in the app/code/Met/Mymodule/view/frontend/templates folder with the following code:

<h1><?php echo $this->getMyModuleTxt(); ?></h1>

Variable $this refer our block class and we are calling the method getMyModuleTxt() which will return the Output.
If all of the above steps are followed, we will see our output string when we open the url http://example.com/mymodule/index/display

Conclusion

This is the easiest way to create a simple Magento2 module. If you find any issues even after following the above steps, you may try clearing all the cache files from the var folder or try the command for upgrading Magento database mentioned above.  We can create more efficient and customized modules based on these steps according to our needs.

STILL SPENDING TIME ON SUPPORT?

Outsource your helpdesk support to save time and money. We have technicians available for little over 5 USD per hour in order to assist your customers with their technical questions. Grow your business and concentrate more on your SALES!

Xieles Support is a provider of reliable and affordable internet services, consisting of Outsourced 24×7 Technical Support, Remote Server Administration, Server Security, Linux Server Management, Windows Server Management and Helpdesk Management to Web Hosting companies, Data centers and ISPs around the world. We are experts in Linux and Windows Server Administration, Advanced Server Security, Server Security Hardening. Our primary focus is on absolute client satisfaction through sustainable pricing, proactively managed services, investment in hosting infrastructure and renowned customer support.