bbc/ipr-webservicekit

Web服务读取层库

v2.0 2017-07-05 12:36 UTC

README

这是一个强大的层,用于以快速、可扩展和弹性的方式从Web服务中读取数据。

Build Status Latest Stable Version Total Downloads License

需求

  • PHP >= 5.6

功能

  • 核心具有弹性、陈旧的验证缓存
  • 完整的监控和日志钩子
  • 轻量级(通常是一个类)的Web服务集成
  • 基于缓存状态的变量cURL超时
  • 多cURL请求
  • 后端断路器保护
  • 框架无关
  • 高度测试和实战证明
  • 单元测试辅助特质,简化Web服务的模拟

背景

该库使从RESTful或基于HTTP的API中读取数据变得简单,无论是公开的、通过API密钥保护的,还是通过SSL证书。

要集成新的后端,库消费者只需创建一个实现了BBC\iPlayerRadio\WebserviceKit\QueryInterface(你甚至可以直接从涵盖大多数基本内容的BBC\iPlayerRadio\WebserviceKit\Query类进行子类化!)的类。

这些查询告诉WebserviceKit如何与后端服务通信,如何缓存它以及如何处理接收到的响应。

基本用法

你只需要在应用中有一个WebserviceKit的实例,然后将Query传递给它。

$client = new GuzzleHttp\Client();
$cache = new BBC\iPlayerRadio\Cache\Cache(new RedisCache());

$service = new BBC\iPlayerRadio\WebserviceKit\Service(
    $client,
    $cache
);

然后你可以定义Query类

<?php

use BBC\iPlayerRadio\WebserviceKit\Query;

class MyBackendQuery extends Query
{
    /**
     * Returns the URL to query, with any parameters applied.
     *
     * @return  string
     */
    public function getURL()
    {
        return 'http://my.service:8080/';
    }

    /**
     * Returns a friendly (and safe) name of the webservice this query hits which we can use in
     * error logging and circuit breakers etc. [a-z0-9-_] please.
     *
     * @return  string
     */
    public function getServiceName()
    {
        return 'my.service';
    }

    /**
     * Given a response from the webservice, this function is called to transform it into something
     * a bit more useful for output.
     *
     * This may be passed a false or a null if the call to the webservice fails, so unit test appropriately.
     *
     * @param   mixed   $response
     * @param   array   $headers
     * @return  mixed
     */
    public function transformPayload($response, array $headers)
    {
        $this->lastHeaders = $headers;
        return $response ? json_decode($response) : $response;
    }
}

获取这些查询就像这样简单

$response = $service->fetch($query);

你还可以同时运行多个查询

list($response1, $response2) = $service->fetch([$query1, $query2]);

这是WebserviceKit最基本的用法,如果需要,其下还有更多强大的功能。

文档

完整的文档可以在仓库的docs/文件夹中找到!