paveldanilin/rest-client

适用于 PHP 7.4+ 的 REST 客户端

2.0.0 2024-02-11 08:01 UTC

README

RestClient 是一个接口,代表执行 REST 请求的主要入口点。

RestClient 是一个便捷的工具,它为 Psr/HttpClient 添加了一系列额外的功能(但它并不打算取代 Psr/HttpClient)

  1. 序列化/反序列化请求/响应体。
  2. 拦截请求(允许在发送请求之前修改请求或处理响应对象)。
  3. 重试策略。

安装

composer require paveldanilin/rest-client

快速示例

创建一个新的 REST 客户端

为了简单起见,我们使用 Guzzle HTTP 客户端,但您可以使用任何 PSR-18 兼容的 HTTP 客户端。

// PSR-18 HTTP client
$httpClient = new GuzzleHttp\Client([
    'base_uri' => 'https://animechan.vercel.app',
]);

// Serializer
$serializer = new \RestClient\Serialization\Symfony\JsonSymfonySerializer();

$restClient = new \RestClient\RestClient($httpClient, $serializer);

定义一个应用程序响应模型

class AnimeQuote
{
    private string $anime = '';
    private string $character = '';
    private string $quote = '';

    public function getAnime(): string
    {
        return $this->anime;
    }

    public function setAnime(string $anime): void
    {
        $this->anime = $anime;
    }

    public function getCharacter(): string
    {
        return $this->character;
    }

    public function setCharacter(string $character): void
    {
        $this->character = $character;
    }

    public function getQuote(): string
    {
        return $this->quote;
    }

    public function setQuote(string $quote): void
    {
        $this->quote = $quote;
    }
}

获取一个对象

请参阅 示例

/** @var AnimeQuote|null $quote */
$quote = $restClient->getForObject('/api/random', AnimeQuote::class);

print "------------------------------------------\n";
print 'Anime:     ' . $quote->getAnime() . "\n";
print 'Character: ' . $quote->getCharacter() . "\n";
print 'Quote:     ' . $quote->getQuote() . "\n";
print "------------------------------------------\n";

获取对象列表

请参阅 示例

/** @var array<ApiModel> $models */
$models = $restClient->getForObject('/api/models', \RestClient\Helpers\asList(ApiModel::class));

拦截请求

拦截器的用法

  • 修改请求头
  • 请求和响应日志记录
  • 根据某些请求参数拒绝请求
  • 更改请求 URL 地址

默认情况下,您可以使用以下拦截器

没有找到合适的拦截器?不要沮丧!创建一个新的拦截器非常简单,只需实现以下接口

interface RequestInterceptorInterface
{
    /**
     * @throws ClientExceptionInterface
     */
    public function intercept(RequestInterface $request, ContextInterface $context, RequestExecutionInterface $execution): ResponseInterface;
}

设置拦截器

$restClient->setInterceptors([
    new \RestClient\Interceptor\RetryInterceptor(), // <- Retry request in case of [429] or [503] response status
    new \RestClient\Interceptor\RequestIdInterceptor(), // <- Add Request-Id header (uuid v4)
    new \RestClient\Interceptor\LogRequestInterceptor($logger), // <- Log before/after and exception
]);