cmdrsharp / guzzle-api

在 Laravel 中使用 Guzzle 的更简洁方法

2.2.0.2 2020-11-17 08:06 UTC

This package is auto-updated.

Last update: 2024-09-17 16:30:03 UTC


README

Latest Stable Version Build Status Scrutinizer Code Quality StyleCI MIT licensed

这是一个 GuzzleHTTP 的 API,旨在使使用 Guzzle 更加简洁并提高可重用性。

要求

  • PHP 7.4 或更高版本
  • Laravel 8.x 或更高版本

请注意,上述要求将始终反映最新版本。较旧版本可能支持较旧的 PHP 和 Laravel 版本。

安装

通过 composer

$ composer require cmdrsharp/guzzle-api

使用方法

将契约注入到需要客户端的类中

/**
 * @var RequestInterface
 */
protected $client;

/**
 * @param Client $client
 */
public function __construct(Client $client)
{
    $this->client = $client;
}

然后您可以通过调用 make 来使用客户端,首先设置基本 URI - 然后填充请求。客户端返回一个正常的 PSR ResponseInterface。这意味着您将像与任何 Guzzle 响应一样与响应交互。

$this->client = $this->client->make('https://httpbin.org/');

$this->client->to('get')->withBody([
	'foo' => 'bar'
])->withHeaders([
	'baz' => 'qux'
])->withOptions([
	'allow_redirects' => false
])->asJson()->get();

echo $response->getBody();
echo $response->getStatusCode();

或者,您可以在一个调用中包含正文、头和选项。

$response = $this->client->to('get')->with([
    'foo' => 'bar'
], [
    'baz' => 'qux'
], [
    'allow_redirects' => false
])->asFormParams()->get();

echo $response->getBody();
echo $response->getStatusCode();

asJson() 方法将通过 Guzzle 请求中的 json 键发送数据。(您可以使用 asFormParams() 将请求作为表单参数发送)。

可用方法 / 示例用法

// GET
$response = $this->client->to('brotli')->get();

// POST
$response = $this->client->to('post')->withBody([
	'foo' => 'bar'
])->asJson()->post();

// PUT
$response = $this->client->to('put')->withBody([
	'foo' => 'bar'
])->asJson()->put();

// PATCH
$response = $this->client->to('patch')->withBody([
	'foo' => 'bar'
])->asJson()->patch();

// DELETE
$response = $this->client->to('delete?id=1')->delete();


// CUSTOM HEADER
$response = $this->client->to('get')->withHeaders([
	'Authorization' => 'Bearer fooBar'
])->asJson()->get();


// CUSTOM OPTIONS
$response = $this->client->to('redirect/5')->withOptions([
	'allow_redirects' => [
		'max' => 5,
		'protocols' => [
			'http',
			'https'
		]
	]
])->get();

调试

在发送请求之前使用 debug(bool|resource) 启用 Guzzle 的调试器,有关更多信息请参阅 此处

每个请求之后都会关闭调试器,如果您需要调试连续发送的多个请求,您需要为所有请求打开调试。

示例

$logFile = './guzzle_client_debug_test.log';
$logFileResource = fopen($logFile, 'w+');

$this->client->debug($logFileResource)->to('post')->withBody([
	'foo' => 'random data'
])->asJson()->post();

fclose($logFileResource);

此操作将 Guzzle 的调试信息写入 guzzle_client_debug_test.log

版本控制

此包遵循 显式版本控制

作者

Dylan DPC CmdrSharp

致谢

灵感来自 Dylan DPC - 当前 1.0.0.0-release 也作为 0.4.0 在他的仓库中提取!它只是重新提交到这里,这样我就可以在未来轻松地根据需要对其进行调整。

许可证

MIT 许可证 (MIT)