moves/api-wrapper

此包已废弃,不再维护。没有建议的替代包。

一个用于快速开发围绕远程API的PHP包装客户端的系统

3.0.1 2023-04-10 16:10 UTC

This package is auto-updated.

Last update: 2023-12-18 17:52:29 UTC


README

介绍

API包装器是一个用于快速开发围绕远程API的PHP包装客户端的系统。在底层使用Guzzle,这个库提供了所有必要的抽象,以便快速配置API请求,无需编写不必要的样板代码。

要深入了解此库的优势,请查看我们的Medium文章

本README中的所有示例都使用了JSONPlaceholder API,这是一个免费使用的REST API,用于测试基本请求。

安装

要将此库添加到您的项目中,请运行

composer require moves/api-wrapper

用法

路由

基本路由

可以使用Route类创建路由。所有路由方法都接受一个唯一的名称和一个URL。

Route::get('post.all', 'https://jsonplaceholder.typicode.com/posts')

唯一的名称用于引用此路由以进行请求(参见请求)。

可用的路由方法

您可以手动声明路由,或使用任何HTTP动词

Route::endpoint('GET', $name, $route);
Route::head($name, $route);
Route::get($name, $route);
Route::post($name, $route);
Route::put($name, $route);
Route::patch($name, $route);
Route::delete($name, $route);
Route::options($name, $route);

每个路由方法都返回一个Endpoint实例,它代表您的路由的所有配置选项。您可以使用其公共成员方法将额外的配置选项(如处理器)应用到端点。

路由组

要将对一组路由应用某些配置选项,请声明一个路由组。路由组可以接受基础URL、单个处理器或处理器组(参见处理器),以及包含路由声明的回调。路由组可以是嵌套的,并且声明在其内部的任何路由都将接收其所有父组的所有配置选项。

Route::group('https://jsonplaceholder.typicode.com', [], function() {
    Route::get('post.all', 'posts');
});

处理器

创建处理器

Laravel中间件的启发,Processor类在请求执行前后拦截请求。处理器可以在请求发送之前修改即将发送的请求,并可以在返回之前检查和修改响应对象。

处理器是应用共享配置选项(如授权头)到即将发送的请求的首选方式(参见请求)。

class AuthorizationProcessor extends Processor
{
    public static function handle(Request $request, callable $next): Response
    {
        $request->headers(['Authorization' => 'token']);

        return $next($request);
    }
}

在请求发送后处理响应,检索由 $next 回调返回的响应对象(参见 响应)。

class PostProcessor extends Processor
{
    public static function handle(Request $request, callable $next): Response
    {
        $response = $next($request);
        
        //Do Something
        
        return $response;
    }
}

应用处理器

您可以将处理器应用于路由和路由组。无论是 Route::group 还是 $endpoint->processor 函数都接受数组或单个处理器类名。

Route::group('https://jsonplaceholder.typicode.com', [GroupProcessor::class], function() {
    Route::get('post.all', 'posts')->processor(EndpointProcessor::class);
});

请求

创建请求

Request 类代表在执行 Guzzle 之前 HTTP 请求的完整配置。创建请求的最佳方式是使用静态的 route 方法,它接受您在声明路由时提供的唯一名称。

$request = Request::route('post.all');

请求路径参数

要设置请求路径参数,必须在路由上使用花括号 {} 声明参数。

Route::get('post.get', 'posts/{id}');

创建请求时,使用 pathParams 方法设置参数值。

$request->pathParams(['id' => 1]);

此请求将解析为 URL https://jsonplaceholder.typicode.com/posts/1

请求查询参数

要设置请求查询(URL)参数,使用 queryParams 方法。

$request->queryParams(['userId' => 1]);

此请求将解析为 URL https://jsonplaceholder.typicode.com/posts?userId=1

请求正文

根据您的需求,可以使用多种方法之一来设置请求正文。

$request->body('body');
$request->json(['key' => 'value']);
$request->formParams(['key' => 'value']);
$request->multipart(['key' => 'value']);

请求头

要配置请求头,使用 headers 方法,它接受键值对数组,包含头名称和值。

$request->headers(['Authorization' => 'token']);

认证

要配置由 Guzzle 定义的认证选项(参见 Guzzle 文档),而不手动设置 Authorization 头,请使用 auth 方法。

$request->auth(['username', 'password']);

选项

要向 Guzzle 传递任何其他配置选项,请使用 options 方法。

$request->options(['timeout' => 3.14]);

Guzzle 客户端

要使用自定义 Guzzle 客户端,请将您的自定义实例传递给 Request::route 方法。这通常用于调试和为测试伪造 Guzzle。

Request::route('post.all', $client);

发送

在配置所有必要的请求选项后,使用 send 方法执行它以接收响应。

$response = $request->send();

方法链

为了方便使用,所有之前提到的请求方法都可以在单个调用中链接。

$response = Request::route('post.get')
    ->pathParams(['id' => 1])
    ->headers(['Authorization' => 'token'])
    ...
    ->send();

响应

执行请求后,您将收到一个 Response 对象。此类实现了 Psr\Http\Message\ResponseInterface,与Guzzle直接返回的响应对象相同(参见 Guzzle 文档),实际上将所有接口方法调用内部转发到Guzzle响应对象实例。然而,此响应对象包含一些额外的功能方法,以提高使用便利性。

获取内容

默认情况下,Guzzle仅以流的形式返回响应体。虽然可以将流转换为普通的 string,但最好使用Response的 getContents 方法。

$body = $response->getContents();

JSON

要自动处理JSON字符串响应的解码,请使用 json 方法。

$data = $response->json();

默认情况下,此方法将JSON字符串解码为关联数组,但若要使用 stdClass 实例代替,请将 false 传递给该方法。

$data = $response->json(false);

资源

Laravel的EloquentStripe PHP库 启发,Resource类以具有基本ORM-like功能的模型实例表示您的API数据。

对于不符合或遵循REST标准的API,资源可能是一个不必要的抽象。然而,对于处理关系对象数据的API,资源提供许多有用的行为。

创建资源

您可以使用自定义ApiResource类表示每个API模型。

class Post extends Resource
{
    ...
}

可用的属性方法

与Eloquent模型一样,资源维护一个内部键/值对数组,表示模型数据,并且有多种方式可以与这些属性交互。

$post = new Post(['id' => 1]);

$post->id = 1;

$id = $post->id;

$post->setAttribute('id', 1);

$id = $post->getAttribute('id');

$post->mergeAttributes(['id' => 1]); //Merge the new attributes into the existing attributes.
                                     //For existing keys, overwrite old values with new, but do not clear other keys.
                                     
$post->setAttributes(['id' => 1]); //Same effect as mergeAttributes.

$post->setAttributes(['id' => 1], true); //Clear all existing attributes.

属性转换

您可以将ApiResource类配置为在设置属性值时将该属性转换为其他类型。

可用的转换类型包括

在您的ApiResource类中声明属性转换类型。

class Post extends Resource
{
    protected $casts = [
        'id' => 'int',
        ...
    ];
}

请注意,如果远程API返回正确类型的数据,则声明转换不是必需的。虽然这不会造成伤害,但除非需要转换,否则您不必担心声明转换类型。

当设置转换属性时,其值将经过一个内部转换函数的处理,并将其作为正确的类型存储在内部。当您将来检索此对象时,它将以存储的类型返回。

属性转换

为了自动将嵌套对象转换为正确的ApiResource类,请使用目标类名作为转换类型。当使用数据关联数组设置属性时,将自动创建目标Resource类的实例。

class Post extends Resource
{
    protected $casts = [
        'user' => 'User::class',
        ...
    ];
}

默认操作

默认情况下,该库为您的ApiResource类提供了基本的CRUD操作实现。通过实现相应的接口合约和使用提供的特质,将这种行为包含到您的类中。

use Moves\ApiWrapper\Resource\Contracts\All as AllContract;
use Moves\ApiWrapper\Resource\Contracts\Create as CreateContract;
use Moves\ApiWrapper\Resource\Contracts\Delete as DeleteContract;
use Moves\ApiWrapper\Resource\Contracts\Get as GetContract;
use Moves\ApiWrapper\Resource\Contracts\Update as UpdateContract;
use Moves\ApiWrapper\Resource\Operations\All;
use Moves\ApiWrapper\Resource\Operations\Create;
use Moves\ApiWrapper\Resource\Operations\Delete;
use Moves\ApiWrapper\Resource\Operations\Get;
use Moves\ApiWrapper\Resource\Operations\Update;
use Moves\ApiWrapper\Resource\Resource;

class Post extends ApiResource implements AllContract, CreateContract, DeleteContract, GetContract, UpdateContract
{
    use All, Create, Delete, Get, Update;
}

在底层,这些操作映射到如上所述的请求层。要执行查询,调用可用的操作方法。

$posts = Post::all();           //Queries post.all Route (usually GET)
                                //returns Collection of Post Resources

$post = Post::create([...]);    //Queries post.create Route (usually POST) using provided attributes
                                //returns instance of Post Resource

$post = new Post([...]);
$post->store();                 //Queries post.create Route (usually POST) using current attributes
                                //Fills $post with returned data
                                
Post::delete(1);                //Queries post.delete (usually DELETE) Route with id = 1

$post = new Post(['id' => 1]);
$post->destroy();               //Queries post.delete Route (usually DELETE) with id = 1

$post = Post::get(1);           //Queries post.get Route (usually GET) with id = 1

$post = new Post(['id' => 1]);
$post = $post->fresh();         //Queries post.get Route (usually GET) with id = 1
                                //Returns new instance of Post Resource
                                
$post = new Post(['id' => 1]);
$post->refresh();               //Queries post.get Route (usually GET) with id = 1
                                //Fills $post with returned data
                                
Post::update(1, [...]);         //Queries post.update Route (usually PUT/PATCH) with id = 1 and current attributes

$post = new Post(['id' => 1]);
$post->updateAttributes([...]); //Sets $post attribues using provided attributes
                                //Queries post.update Route (usually PUT/PATCH) with id = 1 and current attributes
                                //Fills $post with returned data
                                
$post = new Post(['id' => 1]);
$post->saveChanges();           //Queries post.update Route (usually PUT/PATCH) with id = 1 and current attributes
                                //Fills $post with returned data

默认操作路由

默认情况下,每个操作都假设一个特定的路由名,该名称包括模型名称和操作名称。例如,Post::all假设一个名为post.all的路由。如果您需要为任何默认操作设置自定义路由名,请在您的ApiResource类上设置相关属性。

class Post extends ApiResource implements AllContract, CreateContract, DeleteContract, GetContract, UpdateContract
{
    use All, Create, Delete, Get, Update;
    
    protected $allRoute = 'customAllRoute';
    protected $createRoute = 'customCreateRoute';
    protected $deleteRoute = 'customDeleteRoute';
    protected $getRoute = 'customGetRoute';
    protected $updateRoute = 'customUpdateRoute';
}

自定义操作

当然,您可以根据API的需求创建自己的自定义操作。只需定义您需要的方法,并在其中调用Request::route方法。或者,如果您需要覆盖默认操作实现的行为,您应该自己实现合约方法,而不是引入提供默认行为的特质。