Magento 2 frontend controller
In this tutorial I show you how to define and use a Magento 2 frontend controller. It is different than a controller in Magento 1, because there is only one method that can be called. So we need to declare controllers for each action we can set…
Magento 2 frontend controller
Just imagine the following Url structure which you may know from Magento 1 implementation:
http://domain.com/frontName/actionController/actionMethod
In Magento 1 you defined frontName in your config.xml, created a controller Class actionConroller and there you defined a actionMethodAction method. Magento 2 has the same Url structure, but a different file structure. In Magento 2 you need to implement this the following way:
- frontName – is defined in routes.xml configuration and needs to be unique for this shop
- actionController – a folder name inside Controller folder, default is index
- actionMethod – an action class which we call Controller, default is index. Each Controller has only one method, you need one Controller for each action
Define routes.xml
First we need to define our front name. For this create a file etc/frontend/routes.xml with following code:
1 2 3 4 5 6 7 8 | <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd"> <router id="standard"> <route id="mymodulefrontend" frontName="mymodule"> <module name="MyCompany_MyModule" /> </route> </router> </config> |
We can call our controllers now with mymodule as front name.
Create action controller and action method
Each frontend controller extends main Magento class \Magento\Framework\App\Action\Action. You need to implement execute() method, which is the only execute method called from Magento frontend. There you need to implement full action code. For this example I created 2 controllers, one for a success response and a second for a fail response. My success controller looks like this (I created this file under Controller/Response/Success.php:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php namespace MyCompany\MyModule\Controller\Response; class Success extends \Magento\Framework\App\Action\Action { public function execute() { die("Success!"); } } |
Test
You can test your frontend controller by simply call it from your browser. Don’t forget to enable your module first, otherwise you will get a 404 error site.
Conclusion
It is very easy to create a Magento 2 frontend controller. Implementation is different to Magento 1, but in comparison much easier.