dpc / guzzle-client
为 Laravel 应用程序的简单 Guzzle 客户端
v0.4.2
2018-10-02 11:40 UTC
Requires
- php: >=7.1
- guzzlehttp/guzzle: ^6.3
- illuminate/support: 5.5.*||5.6.*||5.7.*
Requires (Dev)
- phpunit/phpunit: ^7.0
This package is not auto-updated.
Last update: 2024-09-26 16:22:26 UTC
README
为 Laravel 应用程序提供简单 Guzzle 客户端
需求
- PHP 7.1 或更高版本
- Laravel 5.5 或 5.6
安装
通过 composer
$ composer require dpc/guzzle-client
使用方法
将合约注入到需要客户端的类中
/** * @var RequestClientContract */ protected $client; /** * @param RequestClientContract $client */ public function __construct(RequestClientContract $client) { $this->client = $client; }
然后,您可以通过首先调用 make 来设置基本 URI - 然后填充请求来使用客户端。客户端返回一个正常的 PSR ResponseInterface。这意味着您将像处理任何 Guzzle 响应一样与响应交互。
$client = $this->client->make('https://httpbin.org/'); $client->to('get')->withBody([ 'foo' => 'bar' ])->withHeaders([ 'baz' => 'qux' ])->withOptions([ 'allow_redirects' => false ])->asJson()->get(); echo $response->getBody(); echo $response->getStatusCode();
或者,您可以在一个调用中包含正文、标头和选项。
$client = $this->client->make('https://httpbin.org/'); $response = $client->to('get')->with([ 'foo' => 'bar' ], [ 'baz' => 'qux' ], [ 'allow_redirects' => false ])->asFormParams()->get(); echo $response->getBody(); echo $response->getStatusCode();
asJson() 方法将使用 Guzzle 请求中的 json 键发送数据。(您可以使用 asFormParams() 将请求发送为表单参数)。
可用方法 / 示例用法
$client = $this->client->make('https://httpbin.org/'); // Get request $response = $client->to('brotli')->get(); // Post request $response = $client->to('post')->withBody([ 'foo' => 'bar' ])->asJson()->post(); // Put request $response = $client->to('put')->withBody([ 'foo' => 'bar' ])->asJson()->put(); // Patch request $response = $client->to('patch')->withBody([ 'foo' => 'bar' ])->asJson()->patch(); // Delete request $response = $client->to('delete?id=1')->delete(); // Headers are easily added using the withHeaders method $response = $client->to('get')->withHeaders([ 'Authorization' => 'Bearer fooBar' ])->asJson()->get(); // Custom options can be specified for the Guzzle instance $response = $client->to('redirect/5')->withOptions([ 'allow_redirects' => [ 'max' => 5, 'protocols' => [ 'http', 'https' ] ] ])->get(); // You can also specify the request method as a string $response = $client->to('post')->withBody([ 'foo' => 'bar' ])->asJson()->request('post');
调试
在发送请求之前使用 debug(bool|resource) 启用 Guzzle 的调试器,更多关于这方面的信息 在这里。
每次请求后都会关闭调试器,如果您需要调试连续发送的多个请求,您需要为所有请求启用调试。
示例
$logFile = './guzzle_client_debug_test.log'; $logFileResource = fopen($logFile, 'w+'); $client->debug($logFileResource)->to('post')->withBody([ 'foo' => 'random data' ])->asJson()->post(); fclose($logFileResource);
这将把 Guzzle 的调试信息写入 guzzle_client_debug_test.log。
版本控制
此包遵循 semver。在主要版本中引入的功能和任何重大更改都将在 发布 中提及。
支持
此包是基于我在几个项目中需要的基于 Guzzle 的基本包装。如果您需要 Guzzle 的其他功能,您可以在这里创建一个 issue 或向 master 分支发送 PR。
如果您需要帮助或有任何问题,您可以
- 在这里创建一个 issue
- 向 @DPC_22 发送推文
- 通过 dylan.dpc@gmail.com 发送邮件
- 在 larachat Slack 团队(@Dylan DPC)上私信我
作者
许可协议
版权所有 (c) 2017 Dylan DPC