How to Create Controller in Magento 2?

How to Create Controller in Magento 2

Controllers in Magento 2, like on other PHP MVC frameworks, are important part of MVC flow. In Magento 2 controllers have only one method (execute) that will be called by front controller. It functionality is that received request, process and render page. In Magento 2 Controller has one or more files in Controller folder of module, it includes actions of class which contain execute() method.

There are 2 different controllers, they are frontend controller and backend controller.

Difference between admin and front controller : Main difference between these two controllers is in additional check and additional methods in admin controller. Both controllers eventually extend \Magento\Framework\App\Action\Action class, but admin controller extend \Magento\Backend\App\Action class, which extends \Magento\Framework\App\Action\Action. Both are generally similar of workflow, but admin controller is a little different. There is a checking permission method in admin controller, it calls form key.

How controller work?

route_name is a unique name which is set in routes.xml.
controller is the folder inside Controller folder.
action is a class with execute method to process request.

Step 1 : Create routes.xml file.

File Path : app/code/V4U/Helloworld/etc/frontend/routes.xml

Step 2: Create controller file

File Path : app/code/V4U/Helloworld/Controller/Index/Index.php

Step 3: Create Layout file

File Path : app/code/V4U/Helloworld/view/frontend/layout/helloworld_index_index.xml

Step 4: Create Block file

File Path : app/code/V4U/Helloworld/Block/Helloworld.php

Step 5: Create template file

File Path : app/code/V4U/Helloworld/view/frontend/templates/helloworld.phtml

Step 6: Run the following Magento commands:

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy -f

php bin/magento cache:clean

Step 7: Launch the url :

Ex : or

🙂 Happy Coding. Keep Liking & Sharing 💻

Tagged , , ,