当前位置: 首页 > 文档资料 > PHP 标准规范 >

PSR-15 HTTP请求消息处理程序的接口建议

优质
小牛编辑
119浏览
2023-12-01

本文档描述了HTTP服务器请求处理程序(request handlers)和HTTP服务器中间件组件(middleware)的常见接口,这些接口使用PSR-7或后续替换PSR所描述的HTTP请求消息。

HTTP请求处理程序是任何Web应用程序的基础部分。 服务器端代码接收请求消息,对其进行处理并生成响应消息。 HTTP中间件是一种将常见请求和响应处理从应用程序层移开的方法。

本文档中描述的接口是请求处理程序和中间件的抽象概念

注意:对“请求处理程序”和“中间件”的所有引用都特定于服务器请求处理。


1: 规范

请求处理程序

  • 请求处理程序是处理HTTP Request请求并生成响应的单个组件,如PSR-7所定义。
  • 如果HTTP Request对象的数据不允许处理器程序生成响应,请求处理程序可能会抛出异常(未定义异常类型)。
  • 使用此标准的请求处理程序必须实现以下接口:
Psr\Http\Server\RequestHandlerInterface

中间件

  • 中间件组件是一个单独的组件,通常与其他中间件组件一起参与处理传入请求和创建结果响应,如PSR-7所定义。
  • 如果满足足够的条件,中间件组件可以创建并返回响应而不委托给请求处理程序。
  • 使用此标准的请求处理程序必须实现以下接口:
Psr\Http\Server\MiddlewareInterface

生成响应

建议生成响应的任何中间件或请求处理程序, 需要实现 PSR-7 ResponseInterface的原型或能够生成ResponseInterface实例的工厂,以防止依赖于特定的HTTP消息内容的实现。

异常处理

建议使用中间件的任何应用程序都包含一个捕获异常并将其转换为响应的组件。 这个中间件 应该 是第一个执行的组件,并包装所有进一步的处理以确保始终生成响应。


2: 接口定义

2.1 Psr\Http\Server\RequestHandlerInterface

必须实现的请求处理器接口:

<?php
namespace Psr\Http\Server;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

interface RequestHandlerInterface
{
    /**
     * 处理传入的请求对象,然后返回响应对象 
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function handle(ServerRequestInterface $request): ResponseInterface;
}

2.2 Psr\Http\Server\MiddlewareInterface

以下接口必须由兼容的中间件组件实现。

<?php
namespace Psr\Http\Server;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Participant in processing a server request and response.
 *
 * An HTTP middleware component participates in processing an HTTP message:
 * by acting on the request, generating the response, or forwarding the
 * request to a subsequent middleware and possibly acting on its response.
 */
interface MiddlewareInterface
{
    /**
     * Process an incoming server request.
     *
     * Processes an incoming server request in order to produce a response.
     * If unable to produce the response itself, it may delegate to the provided
     * request handler to do so.
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
}

建议书解读与应用