czim/laravel-jsonapi

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

Laravel JSON-API 基础。

1.5.4 2020-02-28 10:27 UTC

README

Latest Version on Packagist Software License Build Status Coverage Status

JSON-API 基础

JSON-API 项目的基本应用程序元素。

为 Laravel 应用程序提供快速搭建 JSON-API 兼容性的方法。

此工具 提供设置 API 或用户授权的方法。

免责声明

目前,这还是一个正在进行中的项目。接口和其他重大更改可能会发生。
此项目的旧版(已停用)在 0.9.5 分支。

版本兼容性

Laravel
5.3 1.3
5.4 到 5.6 1.4
5.7 到 6.0 1.5

请注意,版本 1.5+ 需要 PHP 7.1.3+ 和 czim/laravel-dataobject 2.0+。

变更日志

查看变更日志.

安装

通过 Composer

$ composer require czim/laravel-jsonapi

JsonApiServiceProvider 添加到您的 config/app.php

Czim\JsonApi\Providers\JsonApiServiceProvider::class,

发布配置文件。

php artisan vendor:publish

异常

在您的 App\Exceptions\Handler 中,按照如下方式修改 render() 方法

<?php

    public function render($request, Exception $exception)
    {
        if (is_jsonapi_request() || $request->wantsJson()) {
            return jsonapi_error($exception);
        }
        
        // ...

这将使所有 JSON-API(和 JSON)请求抛出的异常以 JSON-API 错误响应的形式显示。

中间件

为了强制正确地设置头部,将 Czim\JsonApi\Http|Middleware\JsonApiHeaders 中间件添加到中间件组或相关路由。您可以通过将其添加到您的 App\Http\Kernel 类来实现这一点

<?php
    protected $middlewareGroups = [
        'api' => [
            // ... 
            \Czim\JsonApi\Http\Middleware\RequireJsonApiHeader::class,
        ],
    ];

请注意,这将 阻止 任何不符合 JSON-API 标准的 HTTP 头部使用方式的 API 消费者访问。

文档

请求数据

请求查询字符串数据

JSON-API 建议使用 GET 参数传递过滤和分页数据,例如

{API URL}?filter[id]=13&page[number]=2

此包提供工具以标准化的方式访问这些信息

使用全局辅助函数 jsonapi_query()。此函数返回 Czim\JsonApi\Support\Request\RequestParser 的单例实例。

<?php
    // Get the full filter data associative array.
    $filter = jsonapi_query()->getFilter();
    
    // Get a specific filter key value, if it is present (with a default fallback).
    $id = jsonapi_query()->getFilterValue('id', 0);
    
    // Get the page number.
    $page = jsonapi_query()->getPageNumber();

当然,您也可以自己实例化请求解析器以访问这些方法

<?php
    // Using the interface binding ...
    $jsonapi = app(\Czim\JsonApi\Contracts\Support\Request\RequestQueryParserInterface::class);
    
    // Or by instantiating it manually ...
    $jsonapi = new \Czim\JsonApi\Support\Request\RequestQueryParser(request());
    
    // After this, the same methods are available
    $id = $jsonapi->getFilterValue('id');

请求体数据

对于以 JSON-API 格式编写的 PUTPOST 请求体,提供特殊的 FormRequests 以验证和访问请求体数据:\Czim\JsonApi\Http\Requests\JsonApiRequest

对于在创建资源时可能省略 idPOST 请求,请使用 \Czim\JsonApi\Http\Requests\JsonApiRequest

这些类可以被扩展并像其他任何 FormRequest 类一样在 Laravel 中使用。

还有全局帮助函数 jsonapi_request()jsonapi_request_create(),它们返回相关请求类的实例(从而模仿 Laravel 的 request())。

使用这种方法可以确保请求通过验证输入与 JSON Schema 一致性来保证是有效的 JSON-API。

<?php
    // Get the root type of the object (which may be 'resource', 'error' or 'meta').
    $rootType = jsonapi_request()->data()->getRootType();
    
    // Get validated data for the current request.
    // This returns an instance of \Czim\JsonApi\Data\Root, which is a data object tree.
    $root = jsonapi_request()->data();
    
    // You can check what kind of resource data is contained.
    if ( ! $root->hasSingleResourceData()) {
        // In this case, the request would either have no "data" key,
        // or it would contain NULL or an array of multiple resources.
    } elseif ($root->hasMultipleResourceData()) {
        // In this case, the request has a "data" key that contains an array of resources.
    }
    
    // Embedded data may be accessed as follows (for single resource).
    $resourceId     = $root->data->id;
    $resourceType   = $root->data->type; 
    $attributeValue = $root->data->attributes->name;
    $relationType   = $root->data->relationships['some-relationship']->data->type;

单个资源请求的请求数据树

Request Data: Single Resource

有关数据对象树的更多信息,请参阅 数据类

编码

此软件包提供了一个编码器,用于根据可变输入内容生成有效的 JSON-API 输出。

经过一些简单的设置,可以生成符合 JSON-API 规范的 JSON 输出,用于 Eloquent 模型和错误。

Eloquent 模型,单个、集合或分页的,将序列化为 JSON-API 资源。

有关编码和配置资源的更多信息

自定义编码和转换

为了为要编码的内容的特定类 FQNs 使用您自己的转换器,请在 jsonapi.transform.map 配置键中映射它们

<?php
    'map' => [
        \Your\ContentClassFqn\Here::class => \Your\TransformerClassFqn\Here::class,        
    ],

此映射将使用 is_a() 检查返回内容的第一匹配项。更具体的匹配项应位于列表更高位置。

作为最后的手段,您始终可以扩展和/或重新绑定 Czim\JsonApi\Encoder\Factories\TransformerFactory 以提供基于给定内容类型的自定义转换器。

贡献

请参阅 CONTRIBUTING 了解详细信息。

鸣谢

许可

MIT 许可证(MIT)。有关更多信息,请参阅 许可文件