jaspr/mapper

JSON API 实现,通过注解或模式。

5.5.0 2024-09-27 14:29 UTC

README

JSON API 标准规范实现

本项目目标是创建一个易于使用的库来实现 JSON API 规范。

整个项目处于开发初期。所以请不要犹豫,欢迎提出好的想法,以使该库更具可定制性和友好性。

库仅提供创建有效 JSON API 文档的包装器。控制器和响应由您自己处理。

问题

您可以发送 电子邮件 或在 gitlab 中创建问题。

安装

使用 Composer 安装库

composer require jaspr/mapper

基本用法

为了简单起见,我们使用 $container 作为某些依赖提供者(依赖注入)。

描述您的对象

您可以选择以哪种方式描述您的对象元数据。

使用注解

注意:如果您想使用注解,您必须在 MetadataFactory 中使用 AnnotationDriver

示例

如您所见,设置资源对象相当简单。只需使用 `#[Attribute]#[Relationship] 注解注释您的获取器即可。

模式

重要部分是实现资源接口。然后填充静态方法 getSchema

注意:如果您想使用模式,您必须在 MetadataFactory 中使用 SchemaDriver

示例

元数据仓库

要创建 MetadataRepository,我们必须使用 MetadataFactory

用法

<?php
/** @var $container Psr\Container\ContainerInterface */
// This is cache instance implements PSR SimpleCache
$cache = $container->get( Psr\SimpleCache\CacheInterface::class);
// This is AnnotationDriver or SchemaDriver, depends on your preferences
$driver = $container->get(\JSONAPI\Driver\Driver::class);
// Paths to your object representing resources
$paths = ['paths/to/your/resources','another/path'];
// Factory returns instance of MetadataRepository
$repository = JSONAPI\Factory\MetadataFactory::create(
            $paths,
            $cache,
            $driver
        );

编码器

选项

参数默认值描述
repositoryMetadataRepository 的实例。

用法

<?php

// First we need DocumentBuilderFactory
// Let's get MetadataRepository from DI
/** @var $container Psr\Container\ContainerInterface */
$metadataRepository = $container->get(JSONAPI\Metadata\MetadataRepository::class);
$encoder = \JSONAPI\Mapper\Encoding\EncoderFactory::createDefaultEncoder($metadataRepository)
$data = new \JSONAPI\Mapper\Test\Resources\Valid\GettersExample('id');
/** @var \JSONAPI\Mapper\Document\ResourceObjectIdentifier $identifier */
$identifier = $encoder->identify($data);
/** @var \JSONAPI\Mapper\Document\ResourceObject $resource */
$resource = $encoder->encode($data);
/** @var \JSONAPI\Mapper\Document\Document $document */
$document = $encoder->compose($data);


请求解析器

此对象与 URL 合作,并解析 JSON API 标准中描述的必需关键字。

选项

参数默认值描述
baseUrlAPI 所在的 URL。必须以 / 结尾,以便与相对链接正确工作。
repositoryMetadataRepository 的实例。
pathParser路径解析器PathParserInterface 的实例。提供有关路径的信息,例如资源类型、资源 ID、关系类型、是否是集合或是否是关系。
paginationParserOffsetStrategyParserPaginationParserInterface 的实例。 分页
sortParser排序解析器SortParserInterface 的实例。 排序
inclusionParser包含解析器InclusionParserInterface 的实例。 包含
fieldsetParser字段集解析器FieldsetParserInterface 的实例。 稀疏字段
filterParser表达式过滤器解析器FilterParserInterface 实例,负责解析过滤器。 过滤器
bodyParser体解析器BodyParserInterface 的实例。
loggerNullLoggerLoggerInterface 实例,PSR 兼容的记录器实例。

过滤器

如上所述,规范对过滤器实现是中立的。因此,我从 OData 中创建(更像是借用)了一个表达式过滤器。现在您可以使用如下所示的语法

?filter=stringProperty eq 'string' and contains(stringProperty,'asdf') and intProperty in (1,2,3) or boolProperty ne true and relation.property eq null

或者如果您有更简单的用例,您可以尝试 QuatrodotFilter

?filter=stringProperty::contains::Bonus|boolProperty::eq::true

分页

我实现了三种分页技术中的两种

  • LimitOffsetPagination
  • PagePagination

包含

https://jsonapi.fullstack.org.cn/format/#fetching-includes

排序

https://jsonapi.fullstack.org.cn/format/#fetching-sorting

首页

如果您想充分利用JASPR SDK,请考虑暴露首页。

<?php
$doc      = new JSONAPI\Mapper\IndexDocument(self::$mr, self::$url);
$response = json_encode($doc);

它返回类似以下内容

{
    "jsonapi": {
        "version": "1.0"
    },
    "links": {
        "relation": "https:\/\/unit.test.org\/relation",
        "getter": "https:\/\/unit.test.org\/getter",
        "meta": "https:\/\/unit.test.org\/meta",
        "prop": "https:\/\/unit.test.org\/prop",
        "third": "https:\/\/unit.test.org\/third"
    },
    "meta": {
        "title": "JSON:API Index Page",
        "baseUrl": "https:\/\/unit.test.org/"
    }
}

如果您的前端使用 jaspr/client-js 库,那么您可以使用 useJsonApiWithIndex 工厂来享受RESTful体验。

开放API模式

此库在OAS周围提供了轻量级包装。它可以生成JSON格式的OAS v3.0.3模式,因此您可以轻松地为您的API提供文档。

基本示例

    $factory = new OpenAPISpecificationBuilder(
        $metadataRepository,
        'https://your.api.url'
    );

    $info = new Info('JSON:API OAS', '1.0.0');
    $info->setDescription('Test specification');
    $info->setContact(
        (new Contact())
            ->setName('Tomas Benedikt')
            ->setEmail('tomas.benedikt@gmail.com')
            ->setUrl('https://gitlab.com/jaspr')
    );
    $info->setLicense(
        (new License('MIT'))
            ->setUrl('https://gitlab.com/jaspr/mapper/-/blob/5.x/LICENSE')
    );
    $info->setTermsOfService('https://gitlab.com/jaspr/mapper/-/blob/5.x/CONTRIBUTING.md');

    $oas = $factory->create($info);
    $oas->setExternalDocs(new ExternalDocumentation('https://gitlab.com/jaspr/mapper/-/wikis/home'));

    $json = json_encode($oas);

有关更多示例,请尝试查看 tests