Create custom router in Magento 2

Custom routers provide a way to modify/replace existing route names with custom ones. For example, if you want to change the current route name learning to custompath you can achieve with it. Below is an example of it.
To do that, we need to add code in frontend/di.xml

<?xml version="1.0"?>
<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">Mage2\CustomRouter\Controller\Router</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">31</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

after that, we need to create Router.php.
Controller/Router.php

<?php

declare(strict_types=1);

namespace Mage2\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 for create custom route for parts
 */
class Router implements RouterInterface
{
    /**
     * @var ActionFactory
     */
    private $actionFactory;

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

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

    /**
     * Class matching routing path and setting custom route
     *
     * @param RequestInterface $request
     * @return ActionInterface|null
     */
    public function match(RequestInterface $request): ?ActionInterface
    {
        $identifier = trim($request->getPathInfo(), '/');

        if (strpos($identifier, 'custompath') !== false) {
            $request->setModuleName('learning');
            $request->setControllerName('index');
            $request->setActionName('index');
            $request->setParams([
                                    'custom_param' => 'custom_value'
                                ]);

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

       return null;
    }
}

Here, in the Router.php file line 51 we are checking if Urlindetifier getting custompath setting learning_index_index layout handle.
Now we need to create a routes.xml file for defining route learning

etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="learning" frontName="learning">
            <module name="Mage2_CustomRouter"/>
        </route>
    </router>
</config>

Need to create a controller file for the learning route.
Controller/Index/Index.php

<?php

declare(strict_types=1);

namespace Mage2\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;

/**
 * Catalog index page controller.
 */
class Index implements HttpGetActionInterface
{
    /**
     * @var PageFactory
     */
    private $pageFactory;

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

    /**
     * Return Part page
     *
     * @return Page
     */
    public function execute(): Page
    {
        // Get the params that were passed from our Router
        $resultPage = $this->pageFactory->create();
        $customParam = $this->request->getParam('custom_param', null);

        return $resultPage;
    }
}

Now we need to create a layout file for that layout handle learning_index_index
view/frontend/layout/learning_index_index.xml

<?xml version="1.0"?>
<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</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Now you can access https://”your.domain.com”/custompath/
it will be showing the same as https://”your.domain.com”/learning/index/index
Custom Router Example Magento2

Need Further Help? or Questions?

Contact Us

Create your account

chatsimple