PHP にて HTTP Client の決定版 Guzzle を使ったサンプル

Guzzle のドキュメントが分かりにくかったのでサンプルを残そうと思う。
Guzzle のインストールは省略。

サンプルコード

  • GET, POST, PATCH, DELETE を使った簡単なサンプル。
  • パラメータの受け渡し確認済み。
  • ヘッダーの追加、変更、Auth など色々追加したい場合はドキュメント

Http.php

use \GuzzleHttp\Client;

class Http
{
	private $client = null;

	private $url = '';


	public function __construct($url = '')
	{
		$this->client = new Client(['verify' => false]);
		$this->url = $url;
	}


	/**
	 * GET でリクエストを投げる
	 *
	 * @param $url: string
	 * @param $param: array('key' => 'value')
	 * @return api result | Client()
	 */
	public function get($url, $param = [], $decode = true)
	{
		$param = (is_array($param)) ? $param : [];

		$res = $this->client->request('GET', $this->url . $url, ['query' => $param]);

		return ($decode) ? $this->decode($res) : $res;
	}


	/**
	 * POST でリクエストを投げる
	 *
	 * @param $url: string
	 * @param $param: array('key' => 'value')
	 * @return api result | Client()
	 */
	public function post($url, $param = [], $decode = true)
	{
		$param = (is_array($param)) ? $param : [];

		$res = $this->client->request('POST', $this->url . $url, ['form_params' => $param]);

		return ($decode) ? $this->decode($res) : $res;
	}


	/**
	 * PATCH でリクエストを投げる
	 *
	 * @param $url: string
	 * @param $param: array('key' => 'value')
	 * @return api result | Client()
	 */
	public function patch($url, $param = [], $decode = true)
	{
		$param = (is_array($param)) ? $param : [];

		$res = $this->client->request('PATCH', $this->url . $url, ['form_params' => $param]);

		return ($decode) ? $this->decode($res) : $res;
	}


	/**
	 * DELETE でリクエストを投げる
	 *
	 * @param $url: string
	 * @param $param: array('key' => 'value')
	 * @return api result | Client()
	 */
	public function delete($url, $param = [], $decode = true)
	{
		$param = (is_array($param)) ? $param : [];

		$multiparts = [];

		foreach ($param as $key => $value) {
			$multiparts[] = [
				'name' => $key,
				'contents' => $value,
			];
		}

		if (count($multiparts) == 0) {
			$multiparts[] = [
				'name' => '',
				'contents' => '',
			];
		}

		$res = $this->client->request('DELETE', $this->url . $url, ['multipart' => $multiparts]);

		return ($decode) ? $this->decode($res) : $res;
	}


	public function decode($client)
	{
		if (empty($client)) {
			return null;
		}

		$body = $client->getBody();

		return (!empty($body)) ? json_decode($body) : null;
	}
}

使い方

use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;

$http = new Http('http://api.sample.com');

try {
	// $http->get(...) を $http->post(...), $http->patch(...), $http->delete(...)
	// などに変更するだけで使用できる。
	$body = $http->get('/users', ['q' => 'smith']);
	var_dump($body);
} catch (ClientException $e) {
	// クライアントエラー
	// ステータスコード
	if ($e->hasResponse()) {
		$statusCode = $e->getResponse()->getStatusCode();
		var_dump($statusCode);
	}
	// エラーのレスポンス
	if ($e->hasResponse()) {
		// echo $e->getResponse()->getBody();
		if (json_decode($e->getResponse()->getBody())) {
			$body = json_decode($e->getResponse()->getBody());
			var_dump($body);
		}
	}
} catch (ServerException $e) {
	// ザーバーエラー
	// ステータスコード
	if ($e->hasResponse()) {
		$statusCode = $e->getResponse()->getStatusCode();
		var_dump($statusCode);
	}
	// エラーのレスポンス
	if ($e->hasResponse()) {
		// echo $e->getResponse()->getBody();
		if (json_decode($e->getResponse()->getBody())) {
			$body = json_decode($e->getResponse()->getBody());
			var_dump($body);
		}
	}
}