edmundluong/php-api-client

在 Guzzle 服务之上提供了一层简单的抽象层

0.5.3 2015-11-10 04:49 UTC

This package is not auto-updated.

Last update: 2024-09-28 17:54:47 UTC


README

Build Status License

为了简化与网络服务进行 API 请求的相关任务,如日志记录和 HTTP 请求签名以进行身份验证,该库在Guzzle Services 客户端上提供了一层简单的抽象层。

安装

PHP API Client 需要 PHP 5.5 或更高版本。通过 Composer 安装此软件包。

composer require "edmundluong/php-api-client"

基本用法

通过扩展 AbstractApiDescription 基类并重写 load() 方法以返回一个包含 API 端点的 new static,定义您要访问的 API 端点。

[有关更多信息,请参阅 Guzzle 服务描述的文档。](http://guzzle3.readthedocs.org/webservice-client/guzzle-service-descriptions.html)

Twitter URLs API 描述的示例

<?php

use Edmund\PhpApiClient\AbstractApiDescription;

class TwitterUrlsApiDescription extends AbstractApiDescription
{
    public function load()
    {
        return new static([
            'additionalProperties' => true,
            'baseUrl'              => 'http://urls.api.twitter.com/1/urls/',
            'operations'           => [
                'count' => [
                    'httpMethod'    => 'GET',
                    'uri'           => 'count.json',
                    'responseModel' => 'JsonResponse',
                    'parameters'    => [
                        'url' => [
                            'type'     => 'string',
                            'location' => 'query',
                            'required' => true
                        ]
                    ]
                ]
            ],
            'models'               => [
                'JsonResponse' => [
                    'type'                 => 'object',
                    'additionalProperties' => [
                        'location' => 'json'
                    ]
                ]
            ]
        ]);
    }
}

要使用 API 客户端消费 API 描述,只需扩展 AbstractApiClient 基类,并将 $apiDescription 字段重写为您的 API 描述类的名称。

<?php

use Edmund\PhpApiClient\AbstractApiClient;

class TwitterUrlsApiClient extends AbstractApiClient
{
    protected $apiDescription = TwitterUrlsApiDescription::class;
}

最后,实例化您的 API 客户端,并使用在 API 描述中的 operations 部分中定义的方法名称进行 API 调用。

<?php

$twitterUrls = new TwitterUrlsApiClient();

$response = $twitterUrls->count(['url' => 'http://www.google.com']);

var_dump($response);

响应

array(2) {
  'count' =>
  int(25256927)
  'url' =>
  string(22) "http://www.google.com/"
}

身份验证器

如果您需要对 API 请求进行身份验证,可以使用 Authenticator 对象对客户端进行身份验证。 Authenticator 对象会截获发出的 HTTP 请求并在发送之前对其进行签名。

这对于需要附加额外参数(例如访问令牌)的 OAuth2 或 HMAC 等各种身份验证流程非常有用。

只需扩展 AbstractAuthenticator 基类,并在 sign() 方法中定义所需的身份验证逻辑。

<?php

use GuzzleHttp\Event\BeforeEvent;
use Edmund\PhpApiClient\Auth\AbstractAuthenticator;

class TwitterUrlsOauthAuthenticator extends AbstractAuthenticator
{
    function sign(BeforeEvent $event)
    {
        $event->getRequest()->getQuery()->add('access_token', 'token_value');
    }
}

在此示例中,TwitterUrlsOauthAuthenticatoraccess_token=token_value 追加到所有 GET 请求中。

为了使用 Authenticator 对客户端进行身份验证,只需将 AbstractApiClient 中的 $authenticators 数组字段重写为 Authenticator 类名的关联数组。

<?php

use Edmund\PhpApiClient\AbstractApiClient;

class TwitterUrlsApiClient extends AbstractApiClient
{
    protected $apiDescription = TwitterUrlsApiDescription::class;
    protected $authenticators = [
        'oauth2' => TwitterUrlsOauthAuthenticator::class
    ];
}

Authenticator 类名映射到的键值(在本例中为 'oauth2')用于在初始化过程中找到客户端所需的 Authenticator 对象。只需在配置数组中将 authType 传递为所需的键,即可将 Authenticator 对象应用于客户端。

<?php

$oauthClient = new TwitterUrlsApiClient(['authType' => 'oauth2']);

$response = $oauthClient->count(['url' => 'http://www.google.com']);

// GET http://urls.api.twitter.com/1/urls/count.json?url=http%3A%2F%2Fwww.google.com&access_token=token_value

调试

AbstractApiClient 基类有一个内置的 LogSubscriber,可以通过在客户端的配置数组中传递一个 debug 标志来打开/关闭它(注意,值必须是 true)。

使用上一个示例中的 OAuth2 客户端

<?php

$oauthClient = new TwitterUrlsApiClient([
    'authType'  => 'oauth2',
    'debug'     => true
]);

$response = $oauthClient->count(['url' => 'http://www.google.com']);

输出

[info] >>>>>>>>
GET /1/urls/count.json?url=http%3A%2F%2Fwww.google.com&access_token=token_value HTTP/1.1
Host: urls.api.twitter.com
User-Agent: Guzzle/5.3.0 curl/7.38.0 PHP/5.6.13-0+deb8u1


<<<<<<<<
HTTP/1.1 200 OK
cache-control: must-revalidate, max-age=900
content-type: application/json;charset=utf-8
expires: Fri, 16 Oct 2015 01:49:46 GMT
last-modified: Fri, 16 Oct 2015 01:34:46 GMT
server: tsa_b
x-connection-hash: f3a8824171a693f97ff1f69e0b675980
x-response-time: 4
Content-Length: 52
Accept-Ranges: bytes
Date: Fri, 16 Oct 2015 01:34:46 GMT
Via: 1.1 varnish
Age: 0
Connection: keep-alive
X-Served-By: cache-tw-iad2-cr1-8-TWIAD2
X-Cache: MISS
X-Cache-Hits: 0
Vary: Accept-Encoding

{"count":25306973,"url":"http:\/\/www.google.com\/"}

此外,还可以将 PSR-3 兼容的 Logger 传递到配置数组中,以便通过传递 debugLogger 选项进行使用。

<?php

$logger = new \Monolog\Logger('name'); 
$twitterUrls = new TwitterUrlsApiClient([
    'debug'         => true,
    'debugLogger'   => $logger
]);

文档

有关更多信息,请参阅官方 Guzzle Web Service 客户端文档。

贡献

请将任何拉取请求提交到 develop 分支。欢迎提交拉取请求,只要贡献的代码遵循 PSR-2 编码风格指南,就会乐意接受。

许可

有关完整的版权和许可信息,请查看与源代码一起分发的 LICENSE 文件。