Magento – How to create custom route in magento2

di.xmlmagento-2.2.5router

I have used below code in di.xml

<type name="Magento\Framework\App\RouterList">
    <arguments>
        <argument name="routerList" xsi:type="array">
            <item name="customrouter" xsi:type="array">
                <item name="class" xsi:type="string">Custom\Catalog\Controller\Router</item>
                <item name="disable" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="string">50</item>
            </item>
        </argument>
    </arguments>
</type>

But i am not able to call the funtion Custom\Catalog\Controller\Router also to tried to exit the code but unable to reach given controller. Can any one give me solution

Best Answer

Using "Magento\Framework\App\RouterList" we use the di.xml file in our module.

app/code/Vendor/Module/etc/di.xml

<type name="Magento\Framework\App\RouterList">
      <arguments>
          <argument name="routerList" xsi:type="array">
              <item name="customrouter" xsi:type="array">
                  <item name="class" xsi:type="string">Vendor\Module\Controller\CustomRouter</item>
                  <item name="disable" xsi:type="boolean">false</item>
                  <item name="sortOrder" xsi:type="string">22</item>
              </item>
          </argument>
      </arguments>
  </type>

After that we need to create a CustomRouter class.

app/code/Vendor/Module/Controller/CustomRouter.php :

namespace Vendor\Module\Controller;
class CustomRouter implements \Magento\Framework\App\RouterInterface
{
   protected $actionFactory;
   protected $_response;
   public function __construct(
       \Magento\Framework\App\ActionFactory $actionFactory,
       \Magento\Framework\App\ResponseInterface $response
   ) {
       $this->actionFactory = $actionFactory;
       $this->_response = $response;
   }
   public function match(\Magento\Framework\App\RequestInterface $request)
   {
       $identifier = trim($request->getPathInfo(), '/');
       if(strpos($identifier, 'customrouter') !== false) {
       $request->setModuleName('customrouter')-> //module name
       setControllerName('index')-> //controller name
       setActionName('index')-> //action name
       setParam('param', 3); //custom parameters
       } else {
           return false;
       }
       return $this->actionFactory->create(
           'Magento\Framework\App\Action\Forward',
           ['request' => $request]
       );
   }
}

And finally you need to create a routes.xml file. app/code/Vendor/Module/etc/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="customrouter" frontName="customrouter">
          <module name="Vendor_Module" />
      </route>
  </router>
</config>
Related Topic