PSR-7、PSR-17和PSR-18的推出都是一项计划的一部分,旨在使
构建需要以 HTTP 客户端无关的方式向服务器发送 HTTP 请求的应用程序
我一直在使用许多历史上严重依赖 Guzzle 而不是抽象接口的应用程序。这些应用程序中的大多数使用包含 JSON 正文的 GET 或 POST 请求以及也包含 JSON 正文的响应来发出简单的 API 请求,或者针对 HTTP 4xx 或 5xx 错误抛出异常。
这个问题来自最近的一个项目,在该项目中,我尝试开发一个 API 包,该包没有明确依赖于 Guzzle,而是仅依赖于 PSR 接口。
这个想法是创建一个ApiWrapper
可以使用以下方式启动的类:
ClientInterface
RequestFactoryInterface
StreamFactoryInterface
这个类将有它需要的任何东西:
ResponseInterface
这样的 API 包装器不会依赖于上述接口的任何具体实现,但它只需要这些接口的任何实现。因此,开发人员将能够使用他或她最喜欢的 HTTP 客户端,而不是被迫使用像 Guzzle 这样的特定客户端。
现在,首先,我真的很喜欢 Guzzle,这不是一篇争论 Guzzle 的精彩的帖子,这只是一篇询问如何让开发人员能够根据他们的需求选择正确的 http 客户端的帖子。
但问题是,显式依赖 Guzzle 提供了许多不错的功能,因为 Guzzle 的功能远不止上述功能。Guzzle 还应用了一系列处理程序和中间件,例如跟踪重定向或抛出 HTTP 4xx 响应异常。
描述很长,但问题来了:如何处理常见的 HTTP 请求处理,例如以下重定向或以受控方式抛出 HTTP 4xx 响应异常(因此无论使用哪种 HTTP 客户端都会产生相同的响应),而无需准确指定使用什么 HTTP 客户端?
下面是一个实现示例ApiWrapper
:
<?php
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
/*
* API Wrapper using PSR-18 ClientInterface, PSR-17 RequestFactoryInterface and PSR-7 RequestInterface
*
* Inspired from: https://www.php-fig.org/blog/2018/11/psr-18-the-php-standard-for-http-clients/
* Require the packages `psr/http-client` and `psr/http-factory`
*
* Details about PSR-7 taken from https://www.dotkernel.com/dotkernel3/what-is-psr-7-and-how-to-use-it/
*
* Class Name Description
* Psr\Http\Message\MessageInterface Representation of a HTTP message
* Psr\Http\Message\RequestInterface Representation of an outgoing, client-side request.
* Psr\Http\Message\ServerRequestInterface Representation of an incoming, server-side HTTP request.
* Psr\Http\Message\ResponseInterface Representation of an outgoing, server-side response.
* Psr\Http\Message\StreamInterface Describes a data stream
* Psr\Http\Message\UriInterface Value object representing a URI.
* Psr\Http\Message\UploadedFileInterface Value object representing a file uploaded through an HTTP request.
*/
class ApiWrapper
{
/**
* The PSR-18 compliant ClientInterface.
*
* @var ClientInterface
*/
private $psr18HttpClient;
/**
* The PSR-17 compliant RequestFactoryInterface.
*
* @var RequestFactoryInterface
*/
private $psr17HttpRequestFactory;
/**
* The PSR-17 compliant StreamFactoryInterface.
*
* @var StreamFactoryInterface
*/
private $psr17HttpStreamFactory;
public function __construct(
ClientInterface $psr18HttpClient,
RequestFactoryInterface $psr17HttpRequestFactory,
StreamFactoryInterface $psr17HttpStreamFactory,
array $options = []
) {
$this->psr18HttpClient($psr18HttpClient);
$this->setPsr17HttpRequestFactory($psr17HttpRequestFactory);
$this->setPsr17HttpStreamFactory($psr17HttpStreamFactory);
}
public function psr18HttpClient(ClientInterface $psr18HttpClient): void
{
$this->psr18HttpClient = $psr18HttpClient;
}
public function setPsr17HttpRequestFactory(RequestFactoryInterface $psr17HttpRequestFactory): void
{
$this->psr17HttpRequestFactory = $psr17HttpRequestFactory;
}
public function setPsr17HttpStreamFactory(StreamFactoryInterface $psr17HttpStreamFactory): void
{
$this->psr17HttpStreamFactory = $psr17HttpStreamFactory;
}
public function makeRequest(string $method, $uri, ?array $headers = [], ?string $body = null): RequestInterface
{
$request = $this->psr17HttpRequestFactory->createRequest($method, $uri);
if (! empty($headers)) {
$request = $this->addHeadersToRequest($request, $headers);
}
if (! empty($body)) {
$stream = $this->createStreamFromString($body);
$request = $this->addStreamToRequest($request, $stream);
}
return $request;
}
/**
* Add headers provided as nested array.
*
* Format of headers:
* [
* 'accept' => [
* 'text/html',
* 'application/xhtml+xml',
* ],
* ]
* results in the header: accept:text/html, application/xhtml+xml
* See more details here: https://www.php-fig.org/psr/psr-7/#headers-with-multiple-values
*
* @param \Psr\Http\Message\RequestInterface $request
* @param array $headers
* @return \Psr\Http\Message\RequestInterface
*/
public function addHeadersToRequest(RequestInterface $request, array $headers): RequestInterface
{
foreach ($headers as $headerKey => $headerValue) {
if (is_array($headerValue)) {
foreach ($headerValue as $key => $value) {
if ($key == 0) {
$request->withHeader($headerKey, $value);
} else {
$request->withAddedHeader($headerKey, $value);
}
}
} else {
$request->withHeader($headerKey, $headerValue);
}
}
return $request;
}
/**
* Use the PSR-7 complient StreamFactory to create a stream from a simple string.
*
* @param string $body
* @return \Psr\Http\Message\StreamInterface
*/
public function createStreamFromString(string $body): StreamInterface
{
return $this->psr17HttpStreamFactory->createStream($body);
}
/**
* Add a PSR 7 Stream to a PSR 7 Request.
*
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\StreamInterface $body
* @return \Psr\Http\Message\RequestInterface
*/
public function addStreamToRequest(RequestInterface $request, StreamInterface $body): RequestInterface
{
return $request->withBody($body);
}
/**
* Make the actual HTTP request.
*
* @param \Psr\Http\Message\RequestInterface $request
* @return \Psr\Http\Message\ResponseInterface
* @throws \Psr\Http\Client\ClientExceptionInterface
*/
public function request(RequestInterface $request): ResponseInterface
{
// According to PSR-18:
// A Client MUST throw an instance of Psr\Http\Client\ClientExceptionInterface
// if and only if it is unable to send the HTTP request at all or if the
// HTTP response could not be parsed into a PSR-7 response object.
return $this->psr18HttpClient->sendRequest($request);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的看法,主要基于尝试了几种方法。
任何PSR-18 客户端都将有一个必须符合的接口。该接口本质上只是一种方法 - sendRequest()
。该方法将发送PSR-7 请求
并返回PSR-7 响应。
请求中的大部分内容将用于构建 PSR-7 请求。sendRequest()
在到达客户之前,这些内容将被组合在一起。PSR-18 规范没有定义客户端的行为,例如是否遵循重定向。它确实指定在出现非 2XX 响应时不应引发异常。
这看起来可能非常有限制,但是这个客户端是线路的末端,它只关心请求的物理发送和响应的捕获。有关客户端行为的所有其他内容都可以内置到 中间件中以扩展该客户端。
那么PSR-18中间件能做什么呢?
sendRequest()
调用,因此可以应用逻辑来处理该调用,例如重试、遵循重定向等。PSR-18 规范没有提到中间件,那么它会放在哪里呢?实现这一点的一种方法是装饰器。装饰器围绕基本 PSR-18 客户端,添加功能,但会将自身呈现为 PSR-18 客户端。这意味着多个装饰器可以在基本客户端上分层,以添加您喜欢的任意数量的功能。
这是 PSR-18 装饰器的示例。这个装饰器本质上什么都不做,但提供了一个将逻辑放入其中的框架。
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class Psr18Decorator implements ClientInterface
{
// ClientInterface
protected $client;
// Instantiate with the current PSR-18 client.
// Options could be added here for configuring the decorator.
public function __construct(ClientInterface $client)
{
$this->client = $client;
}
public function sendRequest(RequestInterface $request): ResponseInterface
{
// The request can be processed here.
// Send the request, just once in this example.
$response = $this->client->sendRequest($request);
// The response can be processed or acted on here.
return $response;
}
// This is added so that if a decorator adds new methods,
// they can be accessed from the top, multiple layers deep.
public function __call($method, $parameters)
{
$result = $this->client->$method(...$parameters);
return $result === $this->client ? $this : $result;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,对于基本的 PSR-18 客户端,它可以这样装饰:
$decoratedPsr18Client = new Psr18Decorator($basePsr18Client);
Run Code Online (Sandbox Code Playgroud)
每个装饰器都可以编写来处理单个问题。例如,如果响应不返回 2XX 代码,您可能希望引发异常。可以编写一个装饰器来做到这一点。
另一个装饰器可以处理 OAuth 令牌,或监视对 API 的访问,以便对其进行速率限制。另一个装饰器可以遵循重定向。
那么,您需要自己编写所有这些装饰器吗?就目前而言,是的,因为不幸的是,周围缺乏它们。然而,由于它们是作为包开发和发布的,因此它们本质上是可重用的代码,可以应用于任何 PSR-18 客户端。
Guzzle 很棒,有很多功能,而且在这方面是单一的。我相信 PSR-18 方法应该允许我们将所有这些功能分解为更小的独立块,以便可以根据需要应用它们。装饰器管理包可能有助于添加这些装饰器(也许确保它们正确排序并且彼此兼容),并且可能以不同的方式处理装饰器自定义方法以避免回退的需要__call()
。
我确信还有其他方法,但这个方法对我来说效果很好。
归档时间: |
|
查看次数: |
2268 次 |
最近记录: |