caciobanu/ guzzle-bundle
guzzle与Symfony的集成包。
v1.1.1
2018-09-13 11:10 UTC
Requires
- php: ^7.1
- guzzlehttp/guzzle: ^6.0
- psr/log: ^1.0
- symfony/framework-bundle: ^4.0
Requires (Dev)
- phpstan/phpstan-shim: ^0.9.2
- phpunit/phpunit: ^7.1
- squizlabs/php_codesniffer: ^3.2
- symfony/yaml: ^4.0
Suggests
- symfony/monolog-bundle: If you want to enable logging and don't want to implement your own 'logger' service.
This package is auto-updated.
Last update: 2024-09-14 03:02:07 UTC
README
安装
您可以使用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中间件是一个两步过程
- 创建一个新的类
<?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; } }
- 创建一个像这样的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开发。