首页 > 语言 > PHP > 正文

使用Zttp简化Guzzle 调用

2024-05-04 23:58:25
字体:
来源:转载
供稿:网友

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 吧!

 

注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选