In this post, we will see how to create a simple custom module in Magento 2.
We are talking about a simple module. So no database and admin related files.
It will have basic module files, controller, block, layout and phtml files.
Let’s get started.

For this, all we need is 7 files. But yes we need it in a necessary folder structure.

Folder structure will be as below. And as you know from our rood directory we place this at app/code/

Magento 2 Simple Custom Module

Magento 2 Simple Custom Module

Now in the image, you can see Vky which is the namespace for our module and Test is our module name.
So for me, the custom module will be Vky_Test. You can choose whatever you want.
For every custom module in Magento 2, we must require two files 1. registration.php and 2. module.xml

Create Vky/Test/registration.php

Create Vky/Test/etc/module.xml

In the module.xml file, you can see setup_version="1.0.0" which is our module version.

Now we are creating a custom module for the frontend and our module name is Vky_Test. So let’s say our module URL will be www.magento2.com/test and for this, we will need a controller.

Create Vky/Test/Controller/Index/Index.php

Now we will need a layout file.
Create Vky/Test/view/frontend/layout/test_index_index.xml

We are using our block and a phtml file so we need to create both files.
Create Vky/Test/Block/Test.php

In  _prepareLayout() function, we are setting our page title.

Create Vky/Test/view/frontend/templates/test.phtml

And in the last most important we need to create routes.xml. In which we can define our frontName so we will able to run our module URL www.magento2.com/test and render content from our test.phtml file.
Create Vky/Test/etc/frontend/routes.xml

See frontName="test" and because of this we can run our module URL by www.magento2.com/test

That’s it. We have created a simple custom module for Magento 2. I hope it helps.

Next:

How to add custom css and js to a custom module? Click here

Now once you know this is how it works then you don’t have to create the same files again and again for your every custom module. You can generate a custom module code from my module creator.

Click here for the Magento 2 Module Creator.

Be kind to one another. Take care!

No Comments

Post A Comment