How To Create a Custom Router in Magento 2?

When working on a project in Magento 2, you should create custom pages with unique URLs. Creating a custom router in Magento 2 involves adding a PHP class responsible for URL request matching and processing. This guide will show you how to build a Magento 2 module, allowing you to define a custom route. 

What is Routing in Magento 2?

In Magento 2, routing establishes a module’s URL. In web applications, routing involves directing data from a URL request to the relevant class for processing. Adobe Commerce and Magento Open Source routing follow the flow outlined here: http://example.com/index.php/router_name/controller/action.

What is the Use of a Custom Router? 

In the development lifecycle, we encounter situations where we must either create a custom URL for our module or modify the route to meet specific requirements.

For instance, if a client requests to create a brand page based on an admin-created brand, fulfilling such a requirement involves implementing custom routers. Let’s proceed to the coding part and create a custom router for our module.

Step-by-Step Guide To Create a Custom Router in Magento 2 

STEP 1:  Create this file to register your module: registration.php

Path: app/code/DCKAP/CustomRouter/registration.php

<?php
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'DCKAP_CustomRouter',
    __DIR__
);

STEP 2: To define your module name you have to create: module.xml

Path: app/code/DCKAP/CustomRouter/etc/module.xml

<?xml version="1.0"?>
<!--
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="DCKAP_CustomRouter" setup_version="1.0.0" />
</config>

STEP 3: To create the router, first, add our custom route to the \Magento\Framework\App\RouterList class. Therefore, you need to create di.xml

Path: app/code/DCKAP/CustomRouter/etc/frontend/di.xml

<?xml version="1.0"?>
<!--
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\App\RouterList">
    <arguments>
        <argument name="routerList" xsi:type="array">
            <item name="customRoute" xsi:type="array">
                <item name="class" xsi:type="string">DCKAP\CustomRouter\Controller\Router</item>
                <item name="disable" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="string">40</item>
            </item>
        </argument>
    </arguments>
</type>
</config>

STEP 4: After defining dependencies, the next step is to create a custom router class. Therefore, you need to create a controller file named: Router.php

Path: app/code/DCKAP/CustomRouter/Controller/Router.php

It will match the custom route name klizer with the existing routing route.

<?php
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
 */

declare(strict_types=1);

namespace DCKAP\CustomRouter\Controller;

use Magento\Framework\App\Action\Forward;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\RouterInterface;

/**
 * Class Router
 */
class Router implements RouterInterface
{
    /**
     * @var ActionFactory
     */
    private $actionFactory;

    /**
     * @var ResponseInterface
     */
    private $response;

    /**
     * Router constructor.
     *
     * @param ActionFactory $actionFactory
     * @param ResponseInterface $response
     */
    public function __construct(
        ActionFactory $actionFactory,
        ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->response = $response;
    }

    /**
     * @param RequestInterface $request
     * @return ActionInterface|null
     */
    public function match(RequestInterface $request): ?ActionInterface
    {
        $identifier = trim($request->getPathInfo(), '/');

        if (strpos($identifier, 'klizer') !== false) {
            $request->setModuleName('routing');
            $request->setControllerName('index');
            $request->setActionName('index');
            $request->setParams([
                'first_param' => 'first_value',
                'second_param' => 'second_value'
            ]);

            return $this->actionFactory->create(Forward::class, ['request' => $request]);
        }

        return null;
    }
}

STEP 5: Now, you need to create your routes.xml file for routing. Therefore, you have to create a routes file named routes.xml.

Path: app/code/DCKAP/CustomRouter/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="routing" frontName="routing">
            <module name="DCKAP_CustomRouter" />
        </route>
    </router>
</config>

STEP 6: Now, you need to create a layout handler for our new route. Therefore, you have to create a layout file named:  routing_index_index.xml

Path: app/code/DCKAP/CustomRouter/view/frontend/layout/routing_index_index.xml

<?xml version="1.0"?>
<!--
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="page.main.title">
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">Custom Routing Page - Klizer By DCKAP</argument>
            </action>
        </referenceBlock>
    </body>
</page>

STEP 7: Now, you need to create the controller that will handle the routing route and retrieve the parameters passed by our router. Therefore, you have to create a controller file named: Index.php. 

Path: app/code/DCKAP/CustomRouter/Controller/Index/Index.php

<?php
/**
 * DCKAP_CustomRouter Extension
 *
 * @category  DCKAP
 * @package   DCKAP_CustomRouter
 * @author    DCKAP
 */

declare(strict_types=1);

namespace DCKAP\CustomRouter\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class Index
 */
class Index implements HttpGetActionInterface
{
    /**
     * @var PageFactory
     */
    private $pageFactory;

    /**
      * @var RequestInterface
      */
    private $request;

    /**
     * @param PageFactory $pageFactory
     * @param RequestInterface $request
     */
    public function __construct(PageFactory $pageFactory, RequestInterface $request)
    {
        $this->pageFactory = $pageFactory;
        $this->request = $request;
    }

    /**
     * @inheritdoc
     */
    public function execute()
    {
        // Get the params that were passed from our Router
        $firstParam = $this->request->getParam('first_param', null);
        $secondParam = $this->request->getParam('second_param', null);

        return $this->pageFactory->create();
    }
}

As a result, accessing the http://example.com/klizer route, the http://example.com/routing/index/index route is loaded.

Screenshot

Conclusion

Magento 2 provides developers with the flexibility to address unique client requests effectively. When creating custom URLs or adjusting routes to meet specific requirements, custom routers prove to be a valuable solution. Whether it’s incorporating a date or location into a product URL, Magento 2’s adaptability allows for tailored solutions that enhance the user experience. Custom routers help navigate the development process, ensuring the final product aligns seamlessly with the client’s vision and needs.

About The Author

We take the guesswork out of ecommerce.
Schedule a consultation call today