Router

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.

Use the snippet in the Magento 2 module creator.

Files

etc/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="" xsi:type="array">
					<item name="class" xsi:type="string">Mage2Gen\Module\Controller\Router</item>
					<item name="disable" xsi:type="boolean">false</item>
					<item name="sortOrder" xsi:type="string">999</item>
				</item>
			</argument>
		</arguments>
	</type>
</config>

Controller/Router.php

<?php
declare(strict_types=1);

namespace Mage2Gen\Module\Controller;

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

class Router implements RouterInterface
{

    protected $transportBuilder;
    protected $actionFactory;

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

    /**
     * {@inheritdoc}
     */
    public function match(RequestInterface $request)
    {
        $result = null;
        
        if ($request->getModuleName() != 'example' && $this->validateRoute($request)) {
            $request->setModuleName('example')
                ->setControllerName('index')
                ->setActionName('index')
                ->setParam('param', 3);
            $result = $this->actionFactory->create(Forward::class);
        }
        return $result;
    }

    /**
     * @param RequestInterface $request
     * @return bool
     */
    public function validateRoute(RequestInterface $request)
    {
        $identifier = trim($request->getPathInfo(), '/');
        return strpos($identifier, '') !== false;
    }
}