欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用Zttp简化Guzzle 调用

程序员文章站 2024-03-11 13:25:01
zttp 是 adam wathan 为了让代码更富表现力以及简化常见用例而写的一个 guzzle 的封装。 这是使用 zttp 去 post 一个自定义头部内容请求...

zttp 是 adam wathan 为了让代码更富表现力以及简化常见用例而写的一个 guzzle 的封装。

这是使用 zttp 去 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',
]);

添加请求头#

$response = zttp::accept('banana/sandwich')->post($url);

防止重定向#

$response = zttp::withoutredirecting()->get($url);

在 zttp 的测试文件 中还有几个简单的示例供你查看。 目前这个包还在开发中,有兴趣的童鞋建议直接上 github 吧!