承接 ffnw/laravel-jsonapi-server 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

ffnw/laravel-jsonapi-server

Composer 安装命令:

composer require ffnw/laravel-jsonapi-server

包简介

This projects provides a library for the Laravel PHP framework which can serve your Eloquent database as jsonapi (http://jsonapi.org/).

README 文档

README

This package is built for the Laravel framework and helps you building a REST API following the json:api-format. It acts as a mapper between your API and the Eloquent database layer (Eloquent services) but also provides support for native data which is not necesarily bound to the database (Native services).

[[TOC]]

Features

The package provides methods for serving resources and resource-collections but also provides methods for handling Create, Update and Delete requests.

Each resource has support for:

  • Request header validation
  • Request body vaidation
  • Links (for HATEOAS)
  • Includes

In addition collections have support for:

  • Pagination
  • Filtering

The package also supports a method for binding JsonApi resource types to Eloquent-Models and JsonApi-Serializers.

The package currently does NOT have support for (contributions welcome!):

  • Creating/Updating/Deleting relations
  • Sparse fields
  • Sorting

3rd Party libraries

For assembling the data we use the tobscure/json-api package.

Terms

  • Serializer: Retrieves data and serializes it into a given format

Basic Usage

Registering the package

To register the package add ApiServer\JsonApi2\Providers\JsonApiServerProvider::class, to the providers-array of your config/app.php.

Building Serializers

For building response in json:api-format we need a serializer which take raw data and serializes it into the wanted format.

We create a serializer class for each resource type that we want to serve in our API. Therefore we create a new directory app/Serializers/ and put our serializer classes inside.

The package already provides an abstract BasicSerializer which you can use as a scaffold to create your own serializers.

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

Binding resource types

At many places the package acts as a mapper between data sources (Native, Eloquent) and an output format. To automate these mappings we need to bind JsonApi-Types to Models and Serializers. This is best done in a seperate service provider.

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

Serving a resource

To serve a resource we usually have a show method in our controller:

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

To serve an Eloquent Resource add

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

return $jsonApiResourceService->buildResponse();

If you want you can set the $id-parameter to null and add whatever constraint you need to the query builder passed in the first parameter. After building the query the service will call firstOrFail to fetch the resource.

Serving a collection of resources

To serve a collection we usually have an index method in our controller:

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

To serve a native Laravel collection

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

return $jsonApiCollectionService->buildResponse();

To serve an Eloquent collection simply add:

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

return $jsonApiCollectionService->buildResponse();

If you have special constraints to yor database query beside the usual includes and filtering options handled by the library you can simply add them to the query instance before passing it to the EloquentCollectionService.

Creating resources

TODO

Updating resorces

TODO

Deleting resources

A method for deleting a resource in your controller usually looks like this:

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

To delete a native resource we initialize the NativeDeleteService with a callback which is called on deletion. Inside the callback we can do whatever we want to delete the resource:

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

To delete an Eloquent resource we just provide a query builder as usual and an id to identify the resource:

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

If you want you can set the $id-parameter to null and add whatever constraint you need to the query builder passed in the first parameter. After building the query the service will call delete() to delete the resource.

Digging deeper

Filtering strategies

Basic

resource?filter[type]=%chased

Advanced

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

Adding custom metadata

Collections

Sorting

http://jsonapi.org/format/#fetching-sorting

Filtering

filter[description]=%D%

Pagination

See http://jsonapi.org/format/#fetching-pagination

Page based (supported)

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

Offset based (curently unsupported; TODO)

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

Curser based (curently unsupported; TODO)

resource?page[curser]=25

Contributing

Submitting patches

Patches can be submitted using the Merge-Request link of our gitlab.

Mailinglist

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

License

See License

ffnw/laravel-jsonapi-server 适用场景与选型建议

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

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

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

围绕 ffnw/laravel-jsonapi-server 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-04-17