mjelamanov/psr18-guzzle

为 Guzzle 6 客户端的 PSR-18 适配器

1.5.0 2024-02-15 06:49 UTC

This package is auto-updated.

Last update: 2024-09-15 07:56:40 UTC


README

Build Status StyleCI Latest Stable Version Total Downloads License

Guzzle 6 客户端提供的 PSR-18 适配器。

需求

PHP 7.0 或更高版本。

安装

composer require mjelamanov/psr18-guzzle

示例

require_once __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\Request;
use Mjelamanov\GuzzlePsr18\Client;

$yourOptionalConfig = [];

$guzzleClient = new GuzzleClient($yourOptionalConfig);

$client = new Client($guzzleClient); // create an adapter instance
$request = new Request('GET', 'http://example.com'); // A PSR-7 request instance

$response = $client->sendRequest($request); // Sending request

var_dump($response->getStatusCode(), (string) $response->getBody()); // Prints response

错误处理

PSR-18 客户端应如何处理错误,请参阅此处。这个库尽量遵循该建议,但 Guzzle 的自定义处理程序可能会破坏这种兼容性。在这种情况下,您可以通过 "新问题" 或发送 "pull request" 告诉我。默认情况下,Guzzle 客户端会抛出 HTTP 400 和 500 错误的异常,这个适配器会捕获这些异常并返回响应。您可以通过 http_errors 选项禁用此行为,但结果将相同。

...

use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;

...

try {
    $response = $client->sendRequest($request);
} catch (NetworkExceptionInterface $e) {
    // Network issues
} catch (RequestExceptionInterface $e) {
    // When request is invalid
} catch (ClientExceptionInterface $e) {
    // In all other cases
}

测试

composer test

许可

MIT 许可证。阅读 LICENSE 文件