Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routes

A route tells Magento which module is responsible for URLs with a certain beginning. Unlike many frameworks, you do not list every page here: a module gets one word in the URL, and Magento finds the rest by folder and class names.

Where the file lives

Storefront routes are described in the module's etc/frontend/routes.xml file. The frontend folder means the storefront area. The file is created by hand.

app/code/Acme/Hello/
├── registration.php
└── etc/
    ├── module.xml
    └── frontend/
        └── routes.xml      new file

The routes.xml file

<?xml version="1.0"?>
<!-- app/code/Acme/Hello/etc/frontend/routes.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="hello" frontName="hello">
            <module name="Acme_Hello"/>
        </route>
    </router>
</config>

Now Magento hands every URL starting with /hello to the Acme_Hello module. After creating the file clean the cache: bin/magento cache:clean. The page itself still returns a 404 error — the module has no action yet, it appears in the next lesson.

AttributeWhat it means
router id="standard"A storefront route; for the admin panel write admin
route idThe internal route name; used in layout file names
frontNameThe first part of the URL

Usually id and frontName are made the same.

What a URL consists of

A Magento URL has three parts: frontName/controller/action. The second part is a folder inside Controller, the third is a class in that folder.

URLClass in the module
/hello/index/indexController\Index\Index
/hello/review/viewController\Review\View
/hello/reviewController\Review\Index
/helloController\Index\Index

A missing part is replaced with the word index. So /hello and /hello/index/index are the same page.

Parameters in the URL

After the three parts you can append parameters as name/value pairs:

/hello/review/view/id/5

The action receives the id parameter with the value 5. The same parameter can be passed the usual way: /hello/review/view?id=5.

Linking to your page

A URL is not typed into a template by hand — the getUrl() method builds it:

<!-- any .phtml template -->
<a href="<?= $escaper->escapeUrl($block->getUrl('hello/review/view', ['id' => 5])) ?>">Review</a>

The method returns a full URL like http://shop.test/hello/review/view/id/5/ that respects the current store view. In PHP classes Magento\Framework\UrlInterface does the same with the same getUrl() method.

Common mistake

A word taken by the core was chosen for frontName: catalog, customer, checkout. The module starts intercepting other URLs, or its own pages do not open. Pick a word that clearly belongs to your module, and do not forget bin/magento cache:clean after editing routes.xml.

Thanks for reading!

Donate to the site — we work hard for you.