Looking at the core Magento 2 code, there seems to be two ways of setting up an admin route.
The first
#File: vendor/magento/module-media-storage/etc/adminhtml/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="adminhtml">
<module name="Magento_MediaStorage" />
</route>
</router>
</config>
is similar to Magento 1. You add your module to a list of modules in the adminhtml
route, and Magento checks it for you.
The second
#File: vendor/magento/module-cms/etc/adminhtml/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="cms" frontName="cms">
<module name="Magento_Cms" before="Magento_Backend" />
</route>
</router>
</config>
has you setting up a new route (id cms
above), and then adding your module to it.
Is one of these the "right/preferred" way of doing this in Magento 2? If not, what are the difference between the two? i.e. when would you use one over the other?
Asking not to solve a specific problem, but to make sure I'm creating my routes in the correct way and that problems similar to Magento 1 modules (pulling in ajax libraries, security, etc.) are avoided.
Best Answer
The difference is in urls. Url has following structure:
<areaFrontName>/<moduleFrontName>/<actionPath>/<actionName>
Route "Adminhtml" has moduleFrontName "admin", same as areaFrontName. So all paths under "adminhtml" route will start with
admin/admin
.If you want to have a more specific url, you should use specific route, like catalog does it. Catalog urls all start with
admin/catalog
. This is the preferred way.So preferred configuration is:
Note that
before="Magento_Backend"
is not needed