How to Create Custom Router in Magento 2

Apr 17, 20182741Gennadiy Haritonov
How to Create Custom Router in Magento 2

We are going on with our Magento 2 tutorials and today we are reviewing the process of custom router creation in Magento 2. This is the second article out of the series devoted to Magento 2 how-to’s, be sure to check out last week’s Part 1, were we explored Controllers, Routers and Responses in Magento 2.

So, how do you create Custom routers in Magento2?

Custom Router

To create a router first you need to add it to the \Magento\Framework\App\RouterList, which is transferred to the Front Controller and contains all the available routers in the right order. To do this, we use the di.xml file in our module.
app/code/Vendor/Module/etc/di.xml:

After that we need to create a CustomRouter class.
app/code/Vendor/Module/Controller/CustomRouter.php:

Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Vlad

And finally we need to create a routes.xml file.
app/code/Vendor/Module/etc/routes.xml:

That was a brief overview of creating Custom Router in Magento 2. As I mentioned before, this is the 2nd part of the 3-part series devoted to Magento 2 tutorials. Part 3 is about to be published soon.


Partner With Us Looking for a partner that will help you to grow your business? We are the right company to develop your webstore. Feel free to get in touch with us. We will be happy to discuss your business opportunities and provide you with a Free Quote. Talk to Vlad

5 Comments

  1. Hi, Jonas. It’s great you appreciated my article, and thanks for the comment.
    A custom router is often used for conducting requests to the standard Magento router, so, depending on the situation, we may need a smaller sortOrder than the standard one.

  2. Thanks for the article, but it little bit confused me:
    1. You define new router with name “customrouter” – don’t work; di.xml must be in etc/fontend or etc/adminhtml
    2. In app/code/Vendor/Module/Controller/CustomRouter.php you change $request object, and make forward
    3. Now standard router have to pick-up request, but it won’t, at least in magento2.3, because standard router sort order is 30 your new router is 22 -> it never fetch request.

  3. Hello, Roman! Thanks for your questions.
    Before I answer them, please bear in mind that the article was written a year ago, and was not tested at Magento 2.3 version.
    1. In this case di.xml will apply both to frontend area and to adminhtml area.
    2. devdocs.magento.com/guides/v2.3/extension-dev-guide/routing.html#custom-routers you can learn here that you should return the router as you make a forward.
    3. Sort order of 22 means that this router will be processed BEFORE the standard router.

Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *