但是传统路由模式没有这个功能。
退回默认路由的功能可以方便统一进行错误处理,尤其是开发api网关的情况。
通过阅读分析框架代码,找到了实现方法,同样涉及的是传统路由的文件。修改如下:
文件: System/Router/AutoRouter.php
方法:public function getRoute(string $uri, string $httpVerb): array
方法:public function getRoute(string $uri, string $httpVerb): array
public function getRoute(string $uri, string $httpVerb): array
{
$segments = explode('/', $uri);
// WARNING: Directories get shifted out of the segments array.
$segments = $this->scanControllers($segments);
//增加变量保存默认Controller名称
$defController = $this->controller;
// If we don't have any segments left - use the default controller;
// If not empty, then the first segment should be the controller
if (! empty($segments)) {
$this->controller = ucfirst(array_shift($segments));
}
$controllerName = $this->controllerName();
//判断Controller是否存在
$file = APPPATH . 'Controllers/' . $this->directory . $controllerName . '.php';
if ($defController !== $this->controller && !is_file($file)) {
//Controller不存在,退回默认Controller,并将段值放入数组
array_unshift($segments, lcfirst($this->controller));
$this->controller = $defController;
$controllerName = $this->controllerName();
}
//end 判断
if (! $this->isValidSegment($controllerName)) {
throw new PageNotFoundException($this->controller . ' is not a valid controller name');
}
{
$segments = explode('/', $uri);
// WARNING: Directories get shifted out of the segments array.
$segments = $this->scanControllers($segments);
//增加变量保存默认Controller名称
$defController = $this->controller;
// If we don't have any segments left - use the default controller;
// If not empty, then the first segment should be the controller
if (! empty($segments)) {
$this->controller = ucfirst(array_shift($segments));
}
$controllerName = $this->controllerName();
//判断Controller是否存在
$file = APPPATH . 'Controllers/' . $this->directory . $controllerName . '.php';
if ($defController !== $this->controller && !is_file($file)) {
//Controller不存在,退回默认Controller,并将段值放入数组
array_unshift($segments, lcfirst($this->controller));
$this->controller = $defController;
$controllerName = $this->controllerName();
}
//end 判断
if (! $this->isValidSegment($controllerName)) {
throw new PageNotFoundException($this->controller . ' is not a valid controller name');
}
上面红色代码是增加的处理逻辑。
其它的没有变更。