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