How to create a simple module in magento 2?

Creating a module in Magento 2, You need to follow below steps,
You must create two entry point file registration.php and module.xml file to module works.

The module is simply residing in app/code folder of Magento instance.

Just Create Folder under the app/code,
For example, We kept Packagename as Rbj and Modulename as Training.
You can keep any name for Packagename/Modulename. In our demo, we have kept Packagename_Modulename as Rbj_Training.

Now start with basic module creation, Registration.php file is for register our module.  Create registration.php file,

Full Path,  app/code/Rbj/Training/registration.php,

 

Create module.xml file,
app/code/Rbj/Training/etc/module.xml,

 

In above file keep name attibute equal to your {Packagename_Modulename}

Now create routes.xml file,
app/code/Rbj/Training/etc/frontend/routes.xml,

 

The frontName attribute is the first part of our custom URL. Default URL structure for Magento 2 like,  <frontName>/<areaControllerFolderName>/<controllerClass>

Where areaControllerFolderName is your area’s controllerFolderName.
An area might be front or admin area. In our case, <areaControllerFolderName> equals Index and   <controllerClass> equals Training.

Create <controllerClass>,
app/code/Rbj/Training/Controller/Index/Training.php

 

In Magento 2 Controller file has execute() method, Its execute when our controller is called.  Now our final URL will look like this, training/index/training

Creating a layout and template files for our module. First , create a training_index_training.xml file in the app/code/Rbj/Training/view/frontend/layout folder with the following code:

 

In the above content, Block class is Rbj\Training\Block\Index\Training, We need to define Block for keeping our templates dynamic function. We will create block further in this tutorial.

Create template file training.phtml for our module representation in frontend,
app/code/Rbj/Training/view/frontend/templates/index/training.phtml,

 

Create Training.php block class for dynamic function which are required to call in our template file.
File path, app/code/Rbj/Training/Block/Index/Training.php

 

Now When you hit the URL, {{Site_Base_Url}}/training/index/training,
You will redirect to 404 page because our module is not installed yet.

For installing our module in Magento 2,  We need to run the command using SSH,  Login with SSH and go to your project root path where Magento is installed,
Run below command,

 

Now You run the URL in the frontend,
{{Site_Base_Url}}/training/index/training
You have display message which you have type in the template file.

Result is,

create simple module in magento 2

 

One Reply to “How to create a simple module in magento 2?”

Leave a Reply

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