grisha-sychev/rest-client

适用于PHP 7.4+的REST客户端

2.0 2024-03-20 19:11 UTC

This package is auto-updated.

Last update: 2024-09-20 20:41:45 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
]);