How To Add Custom router in Magento2

Written by Jigar Patel

May 06, 2023

How To Add Custom router in Magento2

In this article, we will talk to create a custom router in Magento 2.A router is a PHP class responsible for matching and processing of the URL request. In order to add custom router in lib/internal/Magento/Framework/App/RouterList.php we need to add our configuration for the new router in di.xml module.

Steps to Add Custom Router in Magento2

We are already learned how to create a basic module in Magento 2. We need to create module.xml and registration.php files. You can create module.xml and registration.php  from this tutorial.

Here we use Dolphin as the Vendor name and Customize as the module’s name.  You can change this according to your Vendor and Module name.

Step 1: Create a di.xml File

Now we create a di file di.xml in app/code/Dolphin/Customize/etc/frontend folder with the following code.

<?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">Dolphin\Customize\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 2: Create a custom router class

Now we create a class file Router.php in app/code/Dolphin/Customize/Controller folder with the following code.

<?php
declare(strict_types=1);

namespace Dolphin\Customize\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, 'video') !== false) {
            $request->setModuleName('dolphin');
            $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 3: Create a routes.xml file

Now we create a routes file routes.xml in app/code/Dolphin/Customize/etc/frontend folder with the following code.

<?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="dolphin" frontName="dolphin">
            <module name="Dolphin_Customize" />
        </route>
    </router>
</config>

Step 4: Create a layout file

Now we create a layout file dolphin_index_index.xml in app/code/Dolphin/Customize/Controller folder with the following code.

<?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">Dolphin Video Page</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Step 5: Create a controller class

Now we create a class file Index.php in app/code/Dolphin/Customize/Controller/Index folder with the following code.

<?php
declare(strict_types=1);

namespace Dolphin\Customize\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
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();
    }
}

Now execute the below command:

php bin/magento s:up
php bin/magento s:d:c
php bin/magento s:s:d -f
php bin/magento c:c

Result:

Accessing https://jigarmla.demoproject.info/video route,
The https://jigarmla.demoproject.info/dolphin/index/index route is loaded.

Router

 

I Hope, This instruction will be helpful for you.
Happy Coding with magento2!! ?
If you have any difficulties regarding this blog, do consider posting them in the Comments section below!

I’m here to help.
Thank you!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP