Routing is a fundamental part of all MVC frameworks. In order to understand how Magento2 request routing works, it is essential to get familiar with execution flow that leads to certain request getting (or not getting) dispatched.
Routing is the process of determining the current request and validating the request in the router list. After installing front controller and matching a router in the database, Magento should be able to match the URL to a module controller and action name.
Magento 2 Request Routing
- Route determination starts the search for the current route
- Routing process handled by Front Controller and determined in the system
- The “Dispatch” function is built for the routing process in the front controller
Request Process Flow
- Front controller, iterates over available routers to find the current request using match-logic. The request route should be dispatched a maximum of 100 iterations or else its throw an exception.
- RouterList needs to be involved in the routing process. This object is injected from Magento/Framework/App/RouterList.
- Once the current request matches the router list, set the dispatch action as true and also get the response from the “setNoCacheHeader”.
- If the current request does not match the router list, it should throw an exception and the router needs to be forwarded to “noroute” action, i.e. redirected to 404 page.
Structure of Router List:
- Magento 2 is a dependency injection system. Each and every module is allowed to do RouterList.
- For Example: Magento_Store module supplies the Base and DefaultRouter
- Routers are listed based on the sort order item, preferably in ascending order. The Base router always comes before the DefaultRouter.
- In default Magento 2 installation, the DefaultRouter has the lowest priority. It will be the last to be validated for matches in the Front Controller. The DefaultRouter is always redirected to 404 page.
- Once the Base router is processed, it will split into Module, Controller and Action, following which, action will be dispatched and performed with the current request.
Request routing in Magento 2 is a vast topic to dive-in and explore. Hope this blog serves as an introduction to Request Routing.
- Magento 2 Training: Fundamentals of Magento 2 Development
- Magento 2 Codebase: https://github.com/magento/magento2
- Magento 2 Documentation: http://devdocs.magento.com/
- Magento Forums: http://community.magento.com/t5/Core-Technology-Magento-2/ct-p /Magento-2
- Magento 2 Developer Hub: http://www.magento.com/developers/magento2
- Magento 2 Dev Beta Webinar: https://www.youtube.com/watch?v=n9sxhMvW76U
- Merchant Beta Webinar : http://magento.com/blog/technical/magento-2-merchant-beta-release#sthash.FpVsq4YF.dpuf