Chapters Close

How to create a new router in Magento 2?

This article will help you to create a new custom router when developing a store on 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.

Let’s take a real example, you have implemented a custom blog module without the URL Key field, then users and search engine crawlers visiting the blog post will see blog posts link like /blog/id/view/1, /blog/id/view/2 and so on… But this will highly impact your SEO ranking and visibility on the first page of Google search result.

So here the Router class will be helpful to add URL Key to your blog posts. Then it matches the requested url key with the blog post in your Router class and loads the blog page.

This way Google shows the blog link on the first page and your clients will be happy to see the improved SEO & visibility for the blog posts.

Let’s have a look at an example where we will see how to create a custom router. We will create a module with the name Aureatelabs_CustomRouter. And will setup the module with the default configuration in registration.php and module.xml. After that we will create the di.xml file in etc/frontend.

File: di.xml (etc/frontend)

<?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="aureatelabscustomrouter" xsi:type="array">
					<item name="class" xsi:type="string">Aureatelabs\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>

Next we will create Router.php in the Controller folder which contains the logic for the respective router.

<?php
namespace Aureatelabs\CustomRouter\Controller;

/**
 * Aureatelabs Custom router Controller Router
 */
class Router implements \Magento\Framework\App\RouterInterface
{
    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    protected $actionFactory;

    /**
     * Response
     *
     * @var \Magento\Framework\App\ResponseInterface
     */
    protected $_response;

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

    /**
     * @param \Magento\Framework\App\RequestInterface $request
     * @return \Magento\Framework\App\ActionInterface|void
     */
    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $identifier = trim($request->getPathInfo() , '/');
        if (strpos($identifier, 'aureatelabsservice') !== false)
        {
            $request->setModuleName('cms')
                ->setControllerName('page')
                ->setActionName('view')
                ->setParam('page_id', 6);
        }
        else if (strpos($identifier, 'aureatelabsrouter') !== false)
        {
            $request->setModuleName('aureatelabsdemo')
                ->setControllerName('demo')
                ->setActionName('demo');
        }
        else
        {
            return;
        }

        return $this
            ->actionFactory
            ->create('Magento\Framework\App\Action\Forward', ['request' => $request]);
    }
}

In this example we will be searching for two terms ‘aureatelabsservice’ and ‘aureatelabsrouter’.

Now we will add routes.xml file in the frontend. routes.xml (etc/frontend)

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

Create Demo.php (Controller/Demo/Demo.php).

<?php
namespace Aureatelabs\CustomRouter\Controller\Demo;

/**
 * Class Demo
 * @package Aureatelabs\CustomRouter\Controller\Demo
 */
class Demo extends \Magento\Framework\App\Action\Action
{
    protected $_request;

    /**
     * Demo constructor.
     * @param \Magento\Framework\App\Action\Context $context
     */
    public function __construct(\Magento\Framework\App\Action\Context $context)
    {
        parent::__construct($context);
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {
        echo (__METHOD__);
        exit();
    }
}

Now you can enable the module and check for the url with ‘storefronturl/aureatelabsservice’ and ‘storefronturl/aureatelabsrouter’.

The result for the first url will display you the customer service page and second URL will give you results with the name of the method. You can update the method name and test the other URLs as well with your magento setup.

Helpful resources:

Speak your Mind

Post a Comment

Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Grow your online business like 4,565 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.