blueink/snorlax 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

blueink/snorlax

Composer 安装命令:

composer require blueink/snorlax

包简介

A lightweight REST client that gives you full control of your resources

README 文档

README

MIT licensed

Note: this repo is a fork from a snapshot of the github repo ezdeliveryco/snorlax, which no longer exists. Unfortunately, the previous git history / commits were lost.

A light-weight RESTful client built on top of Guzzle that gives you full control of your API's resources. Its based on method definitions and parameters for your URLs. See the usage below.

Installation

Install with Composer

Add the following requirement in your composer.json

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

Install:

composer install

Basic Usage

<?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 'http://localhost/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 http://localhost/api/pokemons?sort=id:asc
$response = $client->pokemons->all([
    'query' => [
        'sort' => 'id:asc',
    ],
]);

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

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

As you can see, each action on your resource is defined an array with two keys, method, defining the HTTP method for the request and path, which defines the path from the base URI returned by the getBaseUri method. You can mock URLs using environment variables as you wish.

Snorlax assume your API returns JSON, so it already returns an StdClass object with the response, decoded by json_decode. If you want to get the raw object returned by Guzzle, use $client->resource->getLastResponse().

Amending the response

As noted above, Snorlax returns an StdClass object, however Resources may overwrite the ->parse() method to manipulate the returned response. This is useful when an API returns a nested set of data such as {'pokemon': {'name':'Mew'}} and you only want the actual data (in this case pokemon). In this example we could use

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

This would return the actual pokemon object. Another scario is that you may want to return a Laravel Collection (Illuminate\Support\Collection) of objects, you could simply do

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

The $method argument is the name of the method which was called to perform the request, such as 'all', or 'get'. This is useful to manipulate different response, such as

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

Another usage could be to cast certain fields are data types. In this example, we'll cast any fields called created_at or updated_at to Carbon isntances

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;
}

Sending parameters and headers

As said before, Snorlax is built on top of Guzzle, so it works basically the same way on passing headers, query strings and request bodies.

<?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',
        ],
    ],
]);

Changing client options

If you want to set default headers for every request you send to the default guzzle client, just use the headers options on your params config key, just like the Guzzle docs.

<?php

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

Setting a base URI

If all your resources are under the same base URI, you can pass it on the constructor instead of declaring on the resource class.

<?php

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

Using a custom client

If you don't want to use Guzzle's default client (or want to mock one), Snorlax accepts any class that implements GuzzleHttp\ClientInterface, so just pass your custom client in the constructor. Can be an instance or a callable.

<?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,
        ]),
    ],
]);

Using a custom cache strategy & driver

If you don't want to use the VolatileRuntime cache driver or even want to change cache strategy, Snorlax allow you to inject any of the stragies and storages provided by 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,
        ],
    ],
]);

Using parallel requests

The parallel pool is made on the top of Guzzle, because of that, you should be using 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();

The result of $requests is a StdClass with postsByUserOne and postsByUserTwo as properties.

Reconnections

Is possible to reconnect when Guzzle throws a GuzzleHttp\Exception\ConnectException. By default, Snorlax tries to reconnect 3 times.

If you want, you can change the number of tries with the retries parameter.

<?php

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

Contributing

Please see the CONTRIBUTING.md file for guidelines.

License

Please see the LICENSE file for License.

blueink/snorlax 适用场景与选型建议

blueink/snorlax 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 88 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 04 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「rest」 「api」 「restful」 「Guzzle」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 blueink/snorlax 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 blueink/snorlax 我们能提供哪些服务?
定制开发 / 二次开发

基于 blueink/snorlax 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 88
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-04-28