ffnw/laravel-jsonapi-server

该项目为Laravel PHP框架提供了一个库,可以将Eloquent数据库作为jsonapi(https://jsonapi.fullstack.org.cn/)提供服务。

1.1.1 2018-05-14 10:10 UTC

This package is auto-updated.

Last update: 2024-09-15 00:41:44 UTC


README

此包为Laravel框架构建,帮助您根据json:api格式构建REST API。它充当API与Eloquent数据库层(Eloquent服务)之间的映射器,但也提供了对非数据库绑定(本地服务)的本地数据支持。

[[目录]]

功能

该包提供了用于提供资源和资源集合的方法,同时也提供了处理创建、更新和删除请求的方法。

每个资源都支持

  • 请求头验证
  • 请求体验证
  • 链接(用于HATEOAS
  • 包含

此外,集合还支持

  • 分页
  • 过滤

该包还支持将JsonApi资源类型绑定到Eloquent-Models和JsonApi-Serializers的方法。

该包目前不支持(欢迎贡献!)

  • 创建/更新/删除关系
  • 稀疏字段
  • 排序

第三方库

为了组装数据,我们使用tobscure/json-api包。

术语

  • 序列化器:检索数据并将其序列化为给定的格式

基本用法

注册包

要注册包,请将ApiServer\JsonApi2\Providers\JsonApiServerProvider::class,添加到您的config/app.php文件中的providers数组。

构建序列化器

为了以json:api格式构建响应,我们需要一个序列化器,它将原始数据序列化为所需的格式。

我们为要在API中提供的服务创建一个资源类型的序列化器类。因此,我们创建一个新的目录app/Serializers/并将我们的序列化器类放入其中。

该包已经提供了一个抽象的BasicSerializer,您可以用它作为创建自己的序列化器的脚手架。

UserSerializer.php

class UserSerializer extends BaseSerializer
{
    protected $type = 'user';

    public function getAttributes($user, array $fields = null)
    {
        if (! ($user instanceof User)) {
            throw new \InvalidArgumentException(
                get_class($this).' can only serialize instances of '.User::class
            );
        }

        return parent::getAttributes($model, $fields);
    }

    public function getLinks($user) {
        $links = [
            'key' => 'value',
        ];

        return $links;
    }

    protected function role($user)
    {
        return $this->hasOne($user, RoleSerializer::class);
    }

    protected function permissions($user)
    {
        return $this->hasMany($user, PermissionSerializer::class);
    }
}

绑定资源类型

在许多地方,该包充当数据源(本地、Eloquent)与输出格式之间的映射器。为了自动化这些映射,我们需要将JsonApi类型绑定到模型和序列化器。这最好在一个单独的服务提供器中完成。

JsonApiResolveServiceProvider.php

class JsonApiResolveServiceProvider extends ServiceProvider
{
    public function register()
    {
        // nothing to do
    }

    public function boot()
    {
        $resolveService = app(ResolveService::class);
        $resolveService->addBinding(
            new ResolveBinding(
                'user',                // type
                UserSerializer::class,  // serializer
                User::class             // model (if type is bound to the database)
            )
        );
    }
}

提供资源

通常,在我们的控制器中有一个用于提供资源的show方法

public function show(Request $request, $id) {
    // code for serving resource
}

要提供Eloquent资源,请添加

$jsonApiResourceService = new EloquentResourceService(
    User::query(),
    $id,
    $request
);

return $jsonApiResourceService->buildResponse();

如果您想,可以将$id参数设置为null,并将您需要的任何约束添加到第一个参数中传递的查询构建器。构建查询后,该服务将调用firstOrFail来获取资源。

提供资源集合

通常,在我们的控制器中有一个用于提供资源的index方法

public function index(Request $request) {
    // code for serving collection
}

要提供本地Laravel集合

$jsonApiCollectionService = new NativeCollectionService(
    collect([]),
    $request
);

return $jsonApiCollectionService->buildResponse();

要提供Eloquent集合,只需添加

$jsonApiCollectionService = new EloquentCollectionService(
    User::query(),
    $request
);

return $jsonApiCollectionService->buildResponse();

如果您在数据库查询中有除通常由库处理的包括和过滤选项之外的任何特殊约束,您可以直接在传递给EloquentCollectionService的查询实例之前添加它们。

创建资源

待办事项

更新资源

待办事项

删除资源

控制器中删除资源的方法通常如下所示

public function destroy(Request $request, $id) {
    // code for deleting resource
}

要删除本地资源,我们使用回调初始化NativeDeleteService,该回调在删除时被调用。在回调内部,我们可以执行任何操作来删除资源。

$deleteService = NativeDeleteService(function() {
    $taskService = new TaskService();
    $taskService->removeTask($id);
});
return $deleteService->buildResponse();

要删除Eloquent资源,我们只需像平常一样提供一个查询构建器和标识资源的ID。

$deleteService = EloquentDeleteService(
    User::query(),
    $id
);
return $deleteService->buildResponse();

如果您愿意,可以将$id参数设置为null,并将所需约束添加到第一个参数中传递的查询构建器。构建查询后,服务将调用delete()来删除资源。

深入了解

过滤策略

基本

resource?filter[type]=%chased

高级

See https://www.drupal.org/docs/8/modules/json-api/filtering

添加自定义元数据

集合

排序

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

过滤

filter[description]=%D%

分页

请参阅https://jsonapi.fullstack.org.cn/format/#fetching-pagination

基于页面(支持)

resource?page[number]=1&page[size]=10

基于偏移量(目前不支持;待办事项)

resource?page[offset]=20&page[limit]=10

基于游标(目前不支持;待办事项)

resource?page[curser]=25

贡献

提交补丁

可以通过我们的gitlab的Merge-Request链接提交补丁。

邮件列表

https://lists.ffnw.de/mailman/listinfo/netmon-dev

许可

请参阅许可