Bof 是一個HTTP客戶端,旨在儘可能方便用戶使用

Bof 是一个HTTP客户端,旨在尽可能方便用户使用

Bof

Bof是一个HTTP客户端,旨在尽可能方便用户使用。

它使最经典的用例(例如下载文件,与JSON API交互或提交表单)尽可能地简单。

由于Bof基于Guzzle,因此可以直接使用Guzzle的方法解决更高级的用例。

综上所述,Bof:

  • 是用户友好的
  • 避免使用魔术字符串和数组进行配置:相反,它提供了可以由IDE自动完成的显式,类型化和文档化的方法
  • 带有默认值:默认支持JSON,4xx和5xx响应抛出异常,默认情况下超时时间短
  • 符合PSR-7

未来的计划:

  • 符合PSR-18(HTTP客户端标准)
  • 弹性机制,例如重试,退避等。

需要简短的插图吗?这是Bof与Guzzle的比较:

// Bof
$http = new Bof\Http;
$createdProduct = $http
 ->withHeader('Authorization', 'Token abcd')
 ->postJson('example.com/api/products', [
 'Hello' => 'world',
 ])
 ->getData();

// Guzzle
$client = new GuzzleHttp\Client([
 'headers' => [
 'Authorization' => 'Token abcd',
 ],
]);
$response = $client->request('POST', 'example.com/api/products', [
 'json' => [
 'Hello' => 'world',
 ]
]);
$createdProduct = json_decode($response->getBody()->__toString(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
 throw new Exception('There was an error while decoding the JSON response');
}

我们需要一个新的HTTP客户端吗?

可能不是。如果该客户端引起了人们的兴趣,这可能意味着我们已经很流行的HTTP客户端可以使用针对简单用例的更简单的API。如果您维护HTTP客户端并且有兴趣,我希望将Bof合并到现有库中。打开一个问题!

安装

composer require mnapoli/bof

用法

$http = new Bof\Http;

$response = $http->get('example.com/api/products');

组态

该Bof\Http班是不可变的

通过调用withXxx()每次都会创建新对象的方法来应用配置:

$http = new Bof\Http;

// The header will apply to all subsequent requests
$http = $http->withHeader('Authorization', "Bearer $token");

请记住,withXxx()方法返回原始客户端的副本:

$http1 = new Bof\Http;

$http2 = $http1->withHeader('Authorization', "Bearer $token");

// $http1 does not have the header applied
// $http2 has the header

由于有了这种模式,可以使用相同的方法仅将配置应用于特定请求:

$ products = $ http- > withHeader(' Authorization ',“ Bearer $ token ”)
-> get(' https://example.com/api/products ')-> getData(); 
 

//下一个请求将*不*具有`Authorization`标头

发送JSON数据

使用JSON方法,数据将自动编码为JSON。甲Content-Type的报头application/json将被添加。

$ http- > postJson(' example.com/api/products ',[ 
' foo ' => ' bar ',]); // putJson()或patchJson()也可以 

发送表格数据

数据也可以作为application/x-www-form-urlencodedPOST请求发送:

$ http- > postForm(' https://example.com/api/products ',[ 
' foo ' => ' bar ',' baz ' => [ ' hi ',' there!' ],]); // putForm()也可以 

超时时间

默认情况下,超时设置为短值:

  • 5秒的请求超时
  • HTTP连接超时为3秒

您可以设置更短或更长时间的超时(或通过将其设置为来禁用它们0):

// 2秒的请求超时,1秒超时连接
$ HTTP = $ HTTP - > withTimeout( 2, 1);

更多使用方法可以查看官方文档

开源地址:

github.com/mnapoli/bof

更多更优质的资讯,请关注我,你的支持会鼓励我不断分享更多更好的优质文章。


分享到:


相關文章: