Home  >  Article  >  Backend Development  >  Zttp simplifies Guzzle calling example sharing

Zttp simplifies Guzzle calling example sharing

小云云
小云云Original
2018-02-10 11:11:441946browse

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();

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());

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',
]);

Patch request


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

Put request


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

Delete request


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

Add request header


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

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!

Statement:
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