Zttp 是一个 Adam Wathan 新发布的 PHP 包,是对 Guzzle 的一个封装,目的是带来丰富的语法和简化常见的用例,而Guzzle 本身使用起来还是相对比较麻烦的。下面是一个带有自定义 Header 的 POST 请求:
$response = Zttp::withHeaders(['Fancy' => 'Pants'])->post($url, [
'foo' => 'bar',
'baz' => 'qux',
]);
$response->json();
使用 Guzzle 实现相同的功能,代码则如下:
$client = new Client();
$response = $client->request('POST', $url, [
'headers' => [
'Fancy' => 'Pants',
],
'form_params' => [
'foo' => 'bar',
'baz' => 'qux',
]
]);
json_decode($response->getBody());
可以看到,Zttp 简化了请求的代码,并自动返回 JSON 响应。
下面是一些 Zttp 的用例:
带有参数的 POST 请求
$response = Zttp::asFormParams()->post($url, [
'foo' => 'bar',
'baz' => 'qux',
]);
Patch 请求
$response = Zttp::patch($this->url('/patch'), [
'foo' => 'bar',
'baz' => 'qux',
]);
Put 请求
$response = Zttp::put($this->url('/put'), [
'foo' => 'bar',
'baz' => 'qux',
]);
Delete 请求
$response = Zttp::delete($this->url('/delete'), [
'foo' => 'bar',
'baz' => 'qux',
]);
添加一个 Accept Header
$response = Zttp::accept('banana/sandwich')->post($url);
阻止重定向
$response = Zttp::withoutRedirecting()->get($url);
在 Zttp 测试文件 中还有一些其他用例,这个包目前还在开发中,更多详情可以通过 Github 了解。