blueink/snorlax

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

1.0.1 2021-04-28 21:35 UTC

This package is auto-updated.

Last update: 2024-09-29 06:25:43 UTC


README

MIT licensed

注意:此仓库是从已不存在的github仓库ezdeliveryco/snorlax的快照中分叉的,因此丢失了之前的git历史/提交。

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

安装

使用Composer安装

在您的composer.json中添加以下依赖项

{
    "require": {
        // ... other requirements
        "blueink/snorlax": "~1.0"
    },
}

安装

composer install

基本用法

<?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参数是调用请求所使用的方法的名称,例如'all'或'get'。这有助于操纵不同的响应,例如

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 文件。