Hello Everyone, Welcome to my blog. First of all, for those people who don’t know anything about me please check out this link for more information.
If you want to connect with me or want to discuss a specific topic, want to share your view or anything, please feel free to write a comment below or write me an email on my email id i.e. ranade.ashish11@gmail.com. I will definitely try to address all your queries. Let’s get started.
Today I am going to discuss how to create a controller in Magento 2. For those folks who missed out on my previous blog (Getting started with Magento 2 Module development), please check out this link and let me know your views on that.
What are controllers
Controllers are one of the most important things in the Magento 2 module development, rather than MVC architecture in general. Magento is using a front controller architecture to process all the requests and responses. The FrontController class is responsible for all functions like, matching the router from a router list, or, dispatching a request to the appropriate controller. You can explore more on this in [code lang=”js”] vendor\magento\framework\App\FrontController.php [/code] Here, the request is matched with the router list and calls the controllers actions i.e execute() method.
Code Patch from FrontController
foreach ($this->_routerList as $router) { try { $actionInstance = $router->match($request); if ($actionInstance) { $result = $this->processRequest( $request, $actionInstance ); break; } } catch (\Magento\Framework\Exception\NotFoundException $e) { $request->initForward(); $request->setActionName('noroute'); $request->setDispatched(false); break; } }
How the Controller works in Magento 2
I am going to discuss just an overview of a request flow (cannot cover every step in this blog as it’s out of the scope for this blog. If you guys need more information on Magento 2 internal routing, please let me know through a comment).
Let’s say for example we have a URL http://asoutions.co.in/ashish/custom/mymodule while processing this URL, Magento explodes this URL using “/” and picks the first parameter as front name(except domain name), the second parameter as your controller name and the third parameter as your action name. So, in this case, we will have
Front name/route_name : Ashish
Controller Name: Custom
Action Name: My module
Find the code snippet from Base Router
$params = explode('/', $path ? $path : $this->pathConfig->getDefaultPath()); foreach ($this->_requiredParams as $paramName) { $output[$paramName] = array_shift($params); }
- front name/route_name is a unique name that is set in routes.xml.
- A controller is a folder inside the Controller folder.
- Action is a class with an execute method to process requests.
There are two types of controller, one for the Admin and another one for the frontend. So, today we are going to cover the frontend controller. Now, its time to do some coding 🙂
I am assuming that you have already installed the latest version of Magento 2 and, created the required files for your module.
Unlike Magento 1, Magento 2 has different configuration files, so, to create a new route for your module, you need to create a routes.xml file inside Namespace/ModuleName/etc/frontend/routes.xml(Here we are going to use Ashish as namespace and FirstModule as Module Name). There are other areas also where we can create our routes.xml like, adminhtml. But, that is beyond the scope of this blog post, for now, we are dealing with the frontend area only.
Once you have created a routes.xml paste in the following content to create a route.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="firstmodule" frontName="firstmodule"> <module name="Ashish_FirstModule"/> </route> </router> </config>
Here, we have defined router-id as “standard”, Magento has different router-id for a different purpose. If you are creating a route for admin, then you should define the router-id as “admin”. We will cover the admin router in future posts. Please check out this link for more information
Once we have created a routes.xml, now, it’s time to create our controller. For that, we have to create a Controller folder inside our module. I.e. Ashish/FirstModule/Controller.
Inside the controller folder, we need to create a folder Index. In Magento 2 controller is considered as a folder and action is considered a PHP class file.
For now, we are creating an Index controller and index action. So, our folder structure should look like this.
Paste in the following code inside your index.php i.e Ashish/FirstModule/Controller/Index/Index.php file
<?php namespace Ashish\FirstModule\Controller\Index; use Magento\Framework\Controller\ResultFactory; /** * Description of Index * * @author Ashish */ class Index extends \Magento\Framework\App\Action\Action { /** * Execute */ public function execute() { $result = $this->resultFactory->create(ResultFactory::TYPE_PAGE); return $result; } }
Our next step is to create a layout file and Block file, we will cover this topic in our next block i.e. working with Layout and Block. That’s all for now, please leave me a comment below what do you feel about this blog.
Goodbye for now and happy coding 🙂
[post-views]