ezdeliveryco/snorlax

该包已被放弃,不再维护。没有建议替代包。

一个轻量级的REST客户端,让您完全控制您的资源

1.1 2017-10-26 22:02 UTC

README

Build Status StyleCI codecov MIT licensed

基于Guzzle构建的轻量级RESTful客户端,让您完全控制API资源。它基于方法定义和URL的参数。下面是使用方法。

基本用法

<?php

use Snorlax\RestResource;
use Snorlax\RestClient;

class PokemonResource extends RestResource
{
    public function getBaseUri()
    {
        // You don't want a raw value like this, use an environment variable :)
        return 'https:///api/pokemons';
    }

    public function getActions()
    {
        return [
            'all' => [
                'method' => 'GET',
                'path' => '/',
            ],
            'get' => [
                'method' => 'GET',
                'path' => '/{0}.json',
            ],
            'create' => [
                'method' => 'POST',
                'path' => '/',
            ],
        ];
    }
}

$client = new RestClient([
    'resources' => [
        'pokemons' => PokemonResource::class,
    ],
]);

// GET https:///api/pokemons?sort=id:asc
$response = $client->pokemons->all([
    'query' => [
        'sort' => 'id:asc',
    ],
]);

// GET https:///api/pokemons/143.json?fields=id,name
$response = $client->pokemons->get(143, [
    'query' => [
        'fields' => 'id,name',
    ],
]);

// POST https:///api/pokemons
$response = $client->pokemons->create([
    'body' => [
        'name' => 'Bulbasaur',
    ],
]);

如您所见,对资源的每个操作都由一个包含两个键的数组定义,method定义请求的HTTP方法,path定义从getBaseUri方法返回的基本URI的路径。您可以使用环境变量来模拟URL。

Snorlax假设您的API返回JSON,因此它已经返回一个由json_decode解码的StdClass对象作为响应。如果您想获取由Guzzle返回的原始对象,请使用$client->resource->getLastResponse()

修改响应

如上所述,Snorlax返回一个StdClass对象,但是资源可以覆盖->parse()方法来操作返回的响应。这在API返回嵌套数据集时很有用,例如{'pokemon': {'name':'Mew'}},您只想获取实际数据(在这种情况下为pokemon)。在这个例子中,我们可以这样做:

public function parse($method, $response)
{
    return $response->pokemon;
}

这将返回实际的pokemon对象。另一个情况是,您可能想返回Laravel Collection(Illuminate\Support\Collection)的对象,您可以这样做:

public function parse($method, $response)
{
    return collect($response->pokemon);
}

$method参数是执行请求的方法名称,例如'所有'或'获取'。这有助于操作不同的响应,例如

public function parse($method, $response)
{
    switch ($method) {
        case 'all':
            return collect($response->pokemon);
            break;
        case 'get':
            return $response->pokemon;
            break;
    }
}

另一种用法是将某些字段转换为数据类型。在这个例子中,我们将任何名为created_atupdated_at的字段转换为Carbon实例

public function parse($action, $response)
{
    $date_fields = [
        'created_at',
        'updated_at',
    ];

    $response = $response->pokemon;

    foreach ($date_fields as $date_field) {
        if (property_exists($response, $date_field)) {
            $response->{$date_field} = Carbon::parse($response->{$date_field});
        }
    }

    return $response;
}

发送参数和头信息

如前所述,Snorlax是基于Guzzle构建的,因此在传递头信息、查询字符串和请求体方面基本相同。

<?php

$pokemons = $client->pokemons->all([
    'query' => [
        'sort' => 'name',
        'offset' => 0,
        'limit' => 150,
    ],
    'headers' => [
        'X-Foo' => 'Bar',
    ],
]);

$pokemons = $client->pokemons->create([
    'body' => [
        'name' => 'Ivysaur',
        'attacks' => [
            'Tackle',
            'Leer',
        ],
    ],
]);

更改客户端选项

如果您想为发送到默认Guzzle客户端的每个请求设置默认头信息,只需在params配置键中使用headers选项,就像Guzzle文档中所述。

<?php

$client = new Snorlax\RestClient([
    'client' => [
        'params' => [
            'headers' => [
                'X-Foo' => 'Bar',
            ],
            'defaults' => [
                'debug' => true,
            ],
            'cache' => true,
        ],
    ],
]);

设置基本URI

如果您的所有资源都在同一基本URI下,您可以在构造函数中传递它,而不是在resource类中声明。

<?php

$client = new Snorlax\RestClient([
    'client' => [
        'params' => [
            'base_uri' => 'https:///api',
        ],
    ],
]);

使用自定义客户端

如果您不想使用 Guzzle 的默认客户端(或想模拟一个),Snorlax 接受任何实现 GuzzleHttp\ClientInterface 的类,所以只需在构造函数中传入您的自定义客户端即可。可以是实例或可调用。

<?php

class MyOwnClient implements GuzzleHttp\ClientInterface
{
    private $config;

    public function __construct(array $params)
    {
        $this->config = $params;
    }
}

// Using a callable to instantiate a new client everytime
$client = new Snorlax\RestClient([
    'client' => [
        'custom' => function(array $params) {
            return new MyOwnClient($params);
        },
        'params' => [
            'param1' => 'value',
        ],
    ],
]);

$client = new Snorlax\RestClient([
    'client' => [
        'custom' => new MyOwnClient([
            'param1' => 1,
        ]),
    ],
]);

使用自定义缓存策略和驱动程序

如果您不想使用 VolatileRuntime 缓存驱动程序,甚至想更改缓存策略,Snorlax 允许您注入由 kevinrob/guzzle-cache-middleware 提供的任何策略和存储。

<?php

$cacheDriver = \Illuminate\Support\Facades\Cache::store('redis');
$cacheStorage = new \Kevinrob\GuzzleCache\Storage\LaravelCacheStorage($cacheDriver);
$cacheStrategy = new \Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy($cacheStorage);

$client = new Snorlax\RestClient([
    'client' => [
        'cacheStrategy' => $cacheStrategy,
        'params' => [
            'cache' => true,
        ],
    ],
]);

使用并行请求

并行池是在 Guzzle 的基础上建立的,因此您应该使用 Guzzle。

<?php
use Snorlax\RestClient;
use Snorlax\RestPool;
use Snorlax\RestResource;

class PostResource extends RestResource
{
    public function getBaseUri()
    {
        return 'https://jsonplaceholder.typicode.com/posts';
    }

    public function getActions()
    {
        return [
            'all' => [
                'method' => 'GET',
                'path' => '/',
            ],
            'show' => [
                'method' => 'GET',
                'path' => '/{0}',
            ],
        ];
    }
}

$client = new RestClient([
    'resources' => [
        'posts' => PostResource::class,
    ],
]);

$pool = new RestPool();

$pool->addResource('postsByUserOne', $client, 'posts.all', [
    'query' => [
        'userId' => '1',
        'cache' => rand(11111, 99999), // bypass cache
    ],
]);

$pool->addResource('postsByUserTwo', $client, 'posts.show', [
    'parameters' => [
        2
    ],
    'query' => [
        'userId' => '2',
        'cache' => rand(11111, 99999), // bypass cache
    ],
]);

$requests = $pool->send();

$requests 的结果是一个具有 postsByUserOnepostsByUserTwo 属性的 StdClass

重连

当 Guzzle 抛出 GuzzleHttp\Exception\ConnectException 时,可以尝试重连。默认情况下,Snorlax 尝试重连 3 次。

如果您愿意,可以使用 retries 参数更改尝试次数。

<?php

$pokemons = $client->pokemons->all([
    'retries' => 3,
    'query' => [
        'limit' => 150,
    ],
]);

贡献

请参阅 CONTRIBUTING.md 文件以获取指南。

许可

请参阅 LICENSE 文件以获取许可。