atijust's blog

技術的なこととか。

PHPのHTTPクライアントライブラリ「Guzzle」を使ってみる(その2)

その1のつづき。

Guzzleには、Service Descriptionといって、インターフェースをJSON(PHP配列でも可)で定義しておけば、コードを一行も書くことなくWebサービスにアクセスできる機能がある。

JSONでAPIのインターフェースを定義して

{
    "operations": {
        "getProfile": {
            "httpMethod": "GET",
            "uri": "/api/restful/v1/people/{+guid}/{+selector}{?fields,format}",
            "parameters": {
                "guid": {
                    "location": "uri"
                },
                "selector": {
                    "location": "uri"
                },
                "fields": {
                    "location": "query"
                },
                "format": {
                    "location": "query",
                    "default": "json"
                }
            }
        }
    }
}

こんなふうに使う。

<?php
require_once 'vendor/autoload.php';

use Guzzle\Plugin\Oauth\OauthPlugin;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

$client = new Client('http://sb.sp.app.mbga.jp/');

$client->addSubscriber(new OauthPlugin(array(
    'consumer_key'    => 'xxxxxxxxxxxxxxxxxxxx',
    'consumer_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
)));

$client->setDescription(ServiceDescription::factory(__DIR__.'/people.json'));

$result = $client->getCommand('getProfile', array(
    'guid'     => '123456',
    'selector' => '@self',
    'fields'   => 'id,nickname',
))->execute();

var_dump($result);

結果は配列以外にも定義次第でいろんな形式で返せる。

array(4) {
  'startIndex' =>
  int(1)
  'person' =>
  array(2) {
    'nickname' =>
    string(7) "hoge"
    'id' =>
    string(17) "sb.mbga.jp:123456"
  }
  'itemsPerPage' =>
  int(1)
  'totalResults' =>
  int(1)
}

動作確認のサンプルなので、ここでは基本的なことしかやってないけど、ドキュメントを読む限りService Descriptionはかなり柔軟で強力な機能のよう。AWS SDK for PHPの実装にも使われていたりするので、実用的なWebサービスクライントの作成も十二分に可能だろう。