如果你的 Slim 应用程序没有可以匹配到当前 HTTP 请求 URI 的路由,程序会调用 Not Found 处理器,并返回一个 HTTP/1.1 404 Not Found
响应到 HTTP 客户端。
默认的 Not Found 处理器
每个 Slim 框架应用程序都有一个默认的 Not Found 处理器。这个处理器将响应状态设置为 404
,并将内容类型设置为 text/html
,它将写入一个简单的异常信息到响应体。
自定义 Not Found 处理器
Slim 框架应用程序的 Not Found 处理器是一个 Pimple 服务。 你可以通过应用程序容器对自定义 Pimple factory 方法进行定义,来创建自定义的 Not Found 处理器取代默认的。
$c = new SlimContainer(); //Create Your container
//Override the default Not Found Handler
$c["notFoundHandler"] = function ($c) {
return function ($request, $response) use ($c) {
return $c["response"]
->withStatus(404)
->withHeader("Content-Type", "text/html")
->write("Page not found");
};
};
//Create Slim
$app = new SlimApp($c);
//... Your code
在这个例子中,我们定义了一个新的 notFoundHandler
factory ,它将返回一个 callable 。返回的 callable 接收2个参数:
- 一个
PsrHttpMessageServerRequestInterface
实例 - 一个
PsrHttpMessageResponseInterface
实例
这个 callable 必须 返回一个恰当的 PsrHttpMessageResponseInterface
实例。