jenky/hermes

Laravel guzzle 管理器

1.4.1 2020-12-11 03:26 UTC

README

Latest Version on Packagist Test Status Quality Score Codecov Total Downloads Software License

该包为 Laravel 应用程序中 Guzzle 提供了一个简洁且易于使用的封装。如果您不知道 Guzzle 是什么,可以查看它们的简介。简单来说,Guzzle 是一个 PHP HTTP 客户端,使得发送 HTTP 请求变得容易,并且可以轻松地与网络服务集成。

安装

您可以使用 Composer 将 Hermes 安装到您的 Laravel 项目中

$ composer require jenky/hermes

安装 Hermes 后,使用 vendor:publish Artisan 命令发布其资产。

php artisan vendor:publish

或者

php artisan vendor:publish --provider="Jenky\Hermes\HermesServiceProvider"

配置

发布 Hermes 的资产后,其主配置文件位于 config/hermes.php。此配置文件允许您配置您的 Guzzle 客户端选项,并且每个配置选项都包含其用途的说明,因此请务必仔细研究此文件。

通道配置

通道只是一个具有自己配置的 Guzzle HTTP 客户端实例。这允许您随时随地在任何地方创建 HTTP 客户端并重复使用。

配置 Guzzle 选项

在通道中设置 Guzzle 请求选项。有关更多信息,请访问 请求选项

'default' => [
    'options' => [
        'base_uri' => 'https://api.github.com/v3/',
        'time_out' => 20,
    ],
],

配置 Guzzle 处理器

在通道内配置 Guzzle 处理器

默认情况下,Guzzle 将根据您的系统上可用的扩展选择最合适的处理器。但是,您可以使用 handler 选项来覆盖此行为。可选地,可以使用 with 配置选项指定处理器需要的任何构造函数参数

'default' => [
    'handler' => App\Http\CustomCurlHandler::class,
    'with' => [
        'delay' => 5,
    ],
],

另一种方法是在 options 配置中设置处理器

'default' => [
    'options' => [
        'handler' => App\Http\CustomCurlHandler::create(['delay' => 5]),
    ],
],

配置 Guzzle 中间件

在通道内配置 Guzzle 中间件

'default' => [
    'middleware' => [
        Jenky\Hermes\Middleware\RequestEvent::class,
    ],
],

您可以在 中间件 部分了解中间件。

请勿在 hermes 配置文件中尝试解决容器绑定实现,例如配置、会话驱动程序、记录器。这是因为当加载 hermes 配置时,这些实现尚未绑定到容器。

'middleware' => [
    // This won't work properly
    GuzzleHttp\Middleware::log(logs(), new GuzzleHttp\MessageFormatter),
],

如果您需要容器绑定实现,请考虑自定义 Guzzle 处理器堆栈而不是在配置中使用中间件。

自定义 Guzzle 处理器堆栈

有时您可能需要完全控制现有通道的 Guzzle HandleStack 的配置。例如,您可能想要为给定通道的处理器堆栈添加、删除或 unshift 一个中间件。

要开始,在通道的配置中定义一个 tap 数组。该 tap 数组应包含应有机会自定义(或“Tap”到)创建后的处理堆栈实例的类列表

'default' => [
    'tap' => [
        App\Http\Client\CustomizeHandlerStack::class,
    ],
],

一旦您已经在通道上配置了tap选项,您就可以定义将定制您的HandlerStack实例的类。这个类只需要一个方法:__invoke,它接收一个GuzzleHttp\HandlerStack实例。

<?php

namespace App\Http\Client;

use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

class CustomizeHandlerStack
{
    /**
     * Customize the given handler stack instance.
     *
     * @param  \GuzzleHttp\HandlerStack  $stack
     * @return void
     */
    public function __invoke(HandlerStack $stack)
    {
        $stack->before('add_foo', Middleware::mapRequest(function (RequestInterface $request) {
            return $request->withHeader('X-Baz', 'Qux');
        }, 'add_baz');
    }
}

所有“tap”类都由服务容器解析,因此它们所需的构造函数依赖项将自动注入。

"Tap" 类参数

“Tap”类还可以接收额外的参数。例如,如果您的处理程序需要使用特定的Laravel日志通道记录Guzzle请求和响应,您可以创建一个接收通道名称作为额外参数的LogMiddleware类。

额外参数将在$stack参数之后传递给类

<?php

namespace App\Support;

use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use Illuminate\Log\LogManager;

class LogMiddleware
{
    /**
     * The logger manager instance.
     *
     * @var \Illuminate\Log\LogManager
     */
    protected $logger;

    /**
     * Create new log middleware instance.
     *
     * @param  \Illuminate\Log\LogManager $logger
     * @return void
     */
    public function __construct(LogManager $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Customize the given handle stack instance.
     *
     * @param  \GuzzleHttp\HandlerStack $stack
     * @return void
     */
    public function __invoke(HandlerStack $stack, ?string $channel = null, string $level = 'debug')
    {
        $stack->push(Middleware::log(
            $this->logger->channel($channel), new MessageFormatter, $level
        ));
    }
}

可以在hermes配置中指定“Tap”类参数,通过在类名和参数之间使用进行分隔。多个参数应以逗号分隔

'default' => [
    'tap' => [
        App\Http\Client\LogMiddleware::class.':slack',
    ],
],

中间件

请求事件

当请求被满足时,此中间件将触发Jenky\Hermes\Events\RequestHandled事件。它具有以下属性

/**
 * The request instance.
 *
 * @var \Psr\Http\Message\RequestInterface
 */
public $request;

/**
 * The response instance.
 *
 * @var \Psr\Http\Message\ResponseInterface|null
 */
public $response;

/**
 * The request options.
 *
 * @var array
 */
public $options;

响应处理器

在发送请求时,默认将使用GuzzleHttp\Psr7\Response作为响应处理程序。但是,您可以配置请求选项以使用您自己的响应处理程序。请注意,响应处理程序必须是Psr\Http\Message\ResponseInterface的实例

'default' => [
    'driver' => 'guzzle',
    'options' => [
        'base_uri' => 'https://httpbin.org/',
        // ...
        'response_handler' => Jenky\Hermes\JsonResponse::class,
    ],
    'middleware' => [
        Jenky\Hermes\Middleware\ResponseHandler::class,
        // ...
    ],
],

json驱动程序将自动使用Jenky\Hermes\Middleware\ResponseHandler中间件,并将默认的response_handler设置为Jenky\Hermes\JsonResponse

现在您的HTTP请求将返回一个Jenky\Hermes\JsonResponse实例,而不是GuzzleHttp\Psr7\Response,后者提供了一系列可能用于检查响应的方法

$response->isSuccessful(): bool;
$response->isError(): bool;
$response->isInformational(): bool;
$response->isRedirect(): bool;
$response->isClientError(): bool;
$response->isServerError(): bool;
$response->ok(): bool;
$response->created(): bool;
$response->badRequest(): bool;
$response->unauthorized(): bool;
$response->forbidden(): bool;
$response->notFound(): bool;
$response->unprocessable(): bool;
$response->serverError(): bool;
$response->header(?string $header = null, $default = null): mixed;
$response->status($code = null);
$response->body(): string;

$response->toArray(): array;
$response->toJson(): string;
$response->exists($key): bool;
$response->get($key, $default = null): mixed;

Jenky\Hermes\JsonResponse对象还实现了PHP的ArrayAccess接口,并支持魔法__get方法,允许您直接在响应上访问JSON响应数据

$response['name'];
// or
$response->name;

使用方法

use Jenky\Hermes\Facades\Guzzle;

Guzzle::get('https://jsonplaceholder.typicode.com/users');
// or using helper
guzzle()->get('https://jsonplaceholder.typicode.com/users');

有时您可能希望向除您应用程序默认通道之外的其他通道发送请求。您可以使用Guzzle外观的channel方法检索并发送到配置文件中定义的任何通道

use Jenky\Hermes\Facades\Guzzle;

Guzzle::channel('my_channel')->get('https://jsonplaceholder.typicode.com/users');
// or using helper
guzzle('my_channel')->get('https://jsonplaceholder.typicode.com/users');

变更日志

有关最近更改的更多信息,请参阅变更日志

测试

$ composer test

贡献

有关详细信息,请参阅贡献行为准则

安全性

如果您发现任何安全相关的问题,请通过电子邮件contact@lynh.me而不是使用问题跟踪器

致谢

许可

MIT许可证(MIT)。有关更多信息,请参阅许可文件