Create a simple module in Magento 2

To develop a custom module. Basically, Magento 2 custom modules are available in the app/code directory with the format of app/code/VendorName/ModuleName.

How to create simple module steps are shown below:

  1. Directory for the module
  2. Configuration for the module
  3. Registration for the module
  4. Front-end router file
  5. Controller file
  6. Block file
  7. Front-end layout file
  8. Front-end template file
  9. Install setup and Enable module

Directory for the module

To create a simple module, we need to set up the structure of the module. So, Let’s now create folders in app/code.

vendor name: namespace name

Helloworld(Folder name ) : module name

Controller: Controls the flow of the module action

Block: Contains the PHP file of the module

etc: Configuration-related file of the module.

etc/frontend: front-end router file will be available here.

view/frontend/layout: frontend layout (XML) file will be available here.

view/frontend/template : frontend template (.phtml) file.

Configuration for the module

First of all, Create a module.xml file in app/code/Module/Helloworld/etc And paste the below code :

Registration of Module

After that, Registration of the module is must be required. So, create registration.php file in app/code/Module/Helloworld/ and paste the below code :

Front-end router file

Then, the front-end router file is used to set the front page’s router name to access at the front side. So, create routes.xml file in app/code/Module/Helloworld/etc/frontend and paste the below code

Controller file

The controller file is used for executing the action of the module. So, create an Index.php file in app/code/Module/Helloworld/Controller/Index and paste the below code :

Front-end layout file

This file is frontend layout file. Create helloworld_index_index.xml file in app/code/Module/Helloworld/view/frontend/layout and paste the below code :

Front-end template file

Now, create helloworld.phtml file in app/code/Module/Helloworld/view/frontend/templates which is used to call block function and also some designing codes

Install setup and Enable module

Now, all things of the module are ready. So, it’s time for the setup module. To set up the module first time, we need to execute the below command :

php bin/magento setup:upgrade

For check the module status :php bin/magento module:enable RH_Helloworld

At last, clean and flush cache :php bin/magento cache:cleanphp bin/magento cache:flush

Leave a comment

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