Zttp簡化Guzzle調用執行個體分享

來源:互聯網
上載者:User
Zttp 是 Adam Wathan 為了讓代碼更富表現力以及簡化常見用例而寫的一個 Guzzle 的封裝。在 PHP 的項目中,如果你需要通過代碼來發起 HTTP 要求,相信很多人對 GuzzleHttp 這個 Package 很熟悉,然而其實在使用 Guzzle 的時候,我們依然可以做得更簡便一點的,本文我們就和大家分享Zttp簡化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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.