What is necessary to create a custom URL structure in Magento 2?

    • Create a new router (e.g. vendor/magento/module-cms/Controller/Router.php) which implements the \Magento\Framework\App\RouterInterface interface. It is easiest to extend an existing router.
  • Register the custom router to the list of routers (e.g. vendor/magento/module-cms/etc/frontend/di.xml)
<type name="Magento\Framework\App\RouterList">
    <arguments>
        <argument name="routerList" xsi:type="array">
            <item name="%name%" xsi:type="array">
                <item name="class" xsi:type="string">%classpath%</item>
                <item name="disable" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="string">%sortorder%</item>
            </item>
        </argument>
    </arguments>
</type>
    • Return an instance of an \Magento\Framework\App\ActionInterface
  • In most cases a custom router will forward the request to the base router by mutating the request (like the CMS router or the default routers do), instead of directly returning an Action instance.

Standard router

A Magento URL that uses the standard router has the following format:

<store-url>/<store-code>/<front-name>/<controller-name>/<action-name>

Where:

  • <store-url> – specifies the base URL for the Magento instance
  • <store-code> – specifies the store context
  • <front-name> – specifies the frontName of the FrontController to use
  • <controller-name> – specifies the name of the controller
  • <action-name> – specifies the action class to execute on the controller class

The standard router parses this URL format and matches it to the correct controller and action.

Leave a Reply

Your email address will not be published. Required fields are marked *