Zttp simplifies Guzzle calling example sharing

小云云
Release: 2023-03-20 08:10:02
Original
1949 people have browsed it

Zttp is a Guzzle wrapper written by Adam Wathan to make the code more expressive and simplify common use cases. In a PHP project, if you need to initiate HTTP requests through code, I believe many people are familiar with the GuzzleHttp Package. However, in fact, when using Guzzle, we can still make it simpler. We will share it with you in this article Zttp simplifies Guzzle calling examples, I hope it can help everyone.

This is an example of using Zttp to post a custom header content request:


$response = Zttp::withHeaders(['Fancy' => 'Pants'])->post($url, [
  'foo' => 'bar',
  'baz' => 'qux',
]);
 
$response->json();
Copy after login

If you use something similar to Guzzle to write this request If so, it would probably be written like this:


$client = new Client();
$response = $client->request('POST', $url, [
  'headers' => [
    'Fancy' => 'Pants',
  ],
  'form_params' => [
    'foo' => 'bar',
    'baz' => 'qux',
  ]
]);
 
json_decode($response->getBody());
Copy after login

In comparison, Zttp simplifies the writing of the code and can easily return content in JSON format.

The following are several examples of using Zttp:

Post request with parameters


#
$response = Zttp::asFormParams()->post($url, [
  'foo' => 'bar',
  'baz' => 'qux',
]);
Copy after login

Patch request


#
$response = Zttp::patch($this->url('/patch'), [
  'foo' => 'bar',
  'baz' => 'qux',
]);
Copy after login

Put request


#
$response = Zttp::put($this->url('/put'), [
  'foo' => 'bar',
  'baz' => 'qux',
]);
Copy after login

Delete request


#
$response = Zttp::delete($this->url('/delete'), [
  'foo' => 'bar',
  'baz' => 'qux',
]);
Copy after login

Add request header


#
$response = Zttp::accept('banana/sandwich')->post($url);
Copy after login

Prevent redirection

$response = Zttp::withoutRedirecting()->get( $url);

Related recommendations:

PHP HTTP client and framework: Guzzle

##About guzzle Installation problem

laravel How to use guzzlehttp/guzzle

The above is the detailed content of Zttp simplifies Guzzle calling example sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template