caciobanu/guzzle-bundle

guzzle与Symfony的集成包。

安装数: 3,081

依赖者: 0

建议者: 0

安全: 0

星标: 1

关注者: 2

分支: 0

公开问题: 0

类型:symfony-bundle

v1.1.1 2018-09-13 11:10 UTC

This package is auto-updated.

Last update: 2024-09-14 03:02:07 UTC


README

这是一个集成Guzzle以简化使用的Symfony包。

Build Status Code Coverage

安装

您可以使用Composer将扩展安装到您的项目中

composer require caciobanu/guzzle-bundle

然后在config/packages/目录下创建一个最小配置文件caciobanu_guzzle.yml

caciobanu_guzzle:
    clients:
        google:
            base_uri: 'https://google.com'

完整的配置如下

caciobanu_guzzle:
    clients:
        google:
            client_class: 'Your\Client'    # You must extend 'GuzzleHttp\Client' which is the default value.
            base_uri: 'https://google.com'
            logging: true                  # Enable logging. Default value: false.
            options:                       # See http://docs.guzzlephp.org/en/stable/request-options.html for all available options.
                timeout: 30
                headers:
                    'User-Agent': 'Test Agent'

使用

在控制器中使用服务

/** @var \GuzzleHttp\Client $client */
$client   = $this->get('caciobanu_guzzle.client.google');
$response = $client->get('/');

添加Guzzle中间件

添加Guzzle中间件是一个两步过程

  1. 创建一个新的类
<?php

namespace App\Guzzle\Middleware;

use Caciobanu\Symfony\GuzzleBundle\Middleware\BeforeRequestMiddlewareInterface;
use Psr\Http\Message\RequestInterface;

class MyMiddleware implements BeforeRequestMiddlewareInterface
{
    public function __invoke(RequestInterface $request): RequestInterface
    {
        // Do something with the request
        return $request;
    }
}
  1. 创建一个像这样的Symfony服务
# config/services.yaml
services:
    App\Guzzle\Middleware\MyMiddleware:
        tags:
            - { name: 'caciobanu_guzzle.middleware', client: 'google' }

可以实现三个中间件接口

  • Caciobanu\Symfony\GuzzleBundle\Middleware\BeforeRequestMiddlewareInterface - 标记在发送请求之前调用的中间件
  • Caciobanu\Symfony\GuzzleBundle\Middleware\AfterResponseMiddlewareInterface - 标记在收到响应后调用的中间件
  • Caciobanu\Symfony\GuzzleBundle\Middleware\OnErrorMiddlewareInterface - 标记在发生错误时调用的中间件
  • Caciobanu\Symfony\GuzzleBundle\Middleware\RetryMiddlewareInterface - 提供重试请求的可能性

致谢

此库由Catalin Ciobanu开发。

许可证

license