Magento 2 magento 2 routing, routing in magento 2

Routing in Magento 2

Routing in Magento is one of the most important parts. Complete application flow depends on act of providing data from a URL request to the appropriate class for processing.

Magento routing uses the following flow:

index.php -> HTTP application -> FrontController -> Routing -> Controller processing -> etc

FrontController class

The FrontController class class searches through a list of routers, provided by the RouterList class, until it matches one that can process a request. When the FrontController finds a matching router, it dispatches the request to an action class returned by the router.

If the FrontController cannot find a router to process a request, it uses the default router.

Router class

The Router class matches a request to an action class that processes the request.

Backend area router

Standard router

A Magento URL that uses the standard router has the following format:

store-url/store-code/front-name/controller-name/action-name

  • store-url :- specifies the base URL for the Magento instance
  • store-code :- specifies the store context
  • front-name :- specifies the frontName of the FrontController to use
  • controller-name :- specifies the name of the controller
  • action-name :- specifies the action class to execute on the controller class
Default router

The default router, defined by the DefaultRouter class, is the last router Magento checks during the routing process. Requests that reach this point often contain invalid URLs that previous routers cannot handle.

Magento uses the default NoRouteHandler to process these requests, but you can write your own no-route handler by implementing the NoRouteHandlerInterface.

Custom routers

Create an implementation of RouterInterface to create a custom router, and define the match() function in this class to use your own route matching logic. If you need route configuration data, use the Route Config class. To add your custom router to the list of routers for the FrontController, add the following entry in your module’s di.xml file:

<type name="Magento\Framework\App\RouterList">
    <arguments>
        <argument name="routerList" xsi:type="array">
            <item name="%name%" xsi:type="array">
                <item name="class" xsi:type="string">%classpath%</item>
                <item name="disable" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="string">%sortorder%</item>
            </item>
        </argument>
    </arguments>
</type>

Where:

  • %name% – The unique name of your router in Magento.
  • %classpath% – The path to your router class.
  • %sortorder% – The sort order of this entry in the router list.

Leave a Reply

Your email address will not be published. Required fields are marked *