Magento 2路由就是定义模块的URL。

整个Magento 2应用程序流基于处理URL请求和路由器类,它们负责匹配和处理请求。

Magento 2中的请求URL是http://example.com/index.php/router_name/controller/action

在这里,router_name用于查找模块。

当在Magento 2中发出请求时,  controller/action:index.php → HTTP app → FrontController → Routing → Controller processing → etc流程。

在Http类中调用FrontController来路由请求,该请求将找到controller/action匹配项。

vendor/magento/framework/App/FrontController.php

public function dispatch(RequestInterface $request)
{
   \Magento\Framework\Profiler::start('routers_match');
   $routingCycleCounter = 0;
   $result = null;
   while (!$request->isDispatched() && $routingCycleCounter++ < 100) {
	   /** @var \Magento\Framework\App\RouterInterface $router */
	   foreach ($this->_routerList as $router) {
		   try {
			   $actionInstance = $router->match($request);
			   if ($actionInstance) {
				   $request->setDispatched(true);
				   $this->response->setNoCacheHeaders();
				   if ($actionInstance instanceof \Magento\Framework\App\Action\AbstractAction) {
					   $result = $actionInstance->dispatch($request);
				   } else {
					   $result = $actionInstance->execute();
				   }
				   break;
			   }
		   } catch (\Magento\Framework\Exception\NotFoundException $e) {
			   $request->initForward();
			   $request->setActionName('noroute');
			   $request->setDispatched(false);
			   break;
		   }
	   }
   }
   \Magento\Framework\Profiler::stop('routers_match');
	if ($routingCycleCounter > 100) {
	   throw new \LogicException('Front controller reached 100 router match iterations');
	}
	return $result;
}

在前端和后台管理上创建自定义路由的步骤:

在实施以下方法之前,您可以参考有关Magento 2模块开发的教程。

创建前端路由:

app/code/[Vendor]/[Module]/etc/frontend 文件夹中创建routes.xml,添加以下代码:

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
	<router id="standard">
		<route frontName="helloworld" id="helloworld">
			<module name="[Vendor]_[Module]"/>
		</route>
	</router>
</config>

创建管理路由:

在app/code/[Vendor]/[Module]/etc/adminhtml文件夹中创建routes.xml,并添加以下代码:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
	<router id="admin">
		<route id="helloworld" frontName="helloworld">
			<module name="[Vendor]_[Module]"/>
		</route>
	</router>
</config>

使用路由重写控制器:

app/code/[Vendor]/[Module]/etc/frontend文件夹中创建routes.xml,并添加以下代码:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
   <router id="standard">
		<route frontName="helloworld" id="helloworld">
			<module name="[Vendor]_[Module]"/>
		</route>
	   <route id="account">
		   <module name="[Vendor]_[Module]" before="Magento_Customer" />
	   </route>
   </router>
</config>
这就是Magento 2路由的全部内容!