phantomwatson / cakephp-json-api
CakePHP的json-api规范插件 - https://jsonapi.fullstack.org.cn/
Requires
- php: >=8.0
- ext-json: *
- ext-mbstring: *
- cakephp/cakephp: ^5.0
- neomerx/json-api: ^4.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-06 06:30:25 UTC
README
此插件实现了neomerx/json-api作为cakephp3的视图类。
JSON API是一个规范,用于描述客户端应该如何请求获取或修改资源,以及服务器应该如何响应这些请求。
JSON API旨在最大限度地减少客户端和服务器之间请求的数量和数据传输量。这种效率的实现不会损害可读性、灵活性和可发现性。
JSON API要求使用JSON API媒体类型(application/vnd.api+json)来交换数据。
安装
您可以使用composer将此插件安装到您的CakePHP应用程序中。
安装composer包的推荐方法是
composer require phantomwatson/cakephp-json-api:dev-master
用法
此插件通过使用其核心中的neomerx/json-api php模块工作,我建议在继续之前先阅读文档。
通过将其添加到bootstrap.php中加载插件
Plugin::load('JsonApi');
或使用cake shell激活它
$ bin/cake plugin load JsonApi
然后告诉您的控制器使用JsonApi视图
$this->viewBuilder()->className('JsonApi.JsonApi');
以下视图变量可以在您的控制器中分配
示例
public function initialize() { $this->viewBuilder()->className('JsonApi.JsonApi'); $this->set('_entities', [ 'Article', 'Author' ]); $this->set('_url', Router::url('/api', true)); $this->set('_meta', ['some' => 'global metadata']); $this->set('_links', [ // uses Neomerx\JsonApi\Schema\Link Link::FIRST => new Link('/authors?page=1'), Link::LAST => new Link('/authors?page=9', [ 'meta' => 'data' ]) ]); } public function index() { $articles = $this->Articles->find() ->all(); $this->set(compact('articles')); $this->set('_serialize', true); // optional parameters $this->set('_include', [ 'articles', 'articles.comments' ]); $this->set('_fieldsets', [ 'articles' => [ 'title' ] ]); }
模式
在_entities
中指定的实体映射到EntitySchema
基类。此类扩展了Neomerx\JsonApi\Schema\SchemaProvider
。
**建议**您为每个定义的实体创建一个模式类,通过扩展EntitySchema类来实现。例如:如果您在Model\Entity\Author
中有一个实体,那么在View\Schema\AuthorSchema
中创建一个模式类。
将模式类视为表示实体的模板。
由于这个原因,您可以访问当前视图对象以及请求和助手。如果需要,您可以在模式内部调用$this->getView()
。
模式示例
示例 App\View\Schema\AuthorSchema.php (映射到 App\Model\Entity\Author)
<?php namespace TestApp\View\Schema; use JsonApi\View\Schema\EntitySchema; class AuthorSchema extends EntitySchema { public function getId($entity) { return $entity->get('id'); } public function getAttributes($entity) { return [ 'title' => $entity->title, 'body' => $entity->body, 'published' => $entity->published, 'helper_link' => $this->Url->build(['action' => 'view']) // view helper ]; } public function getRelationships($entity, array $includeRelationships = []) { return [ 'articles' => [ self::DATA => $entity->articles ] ]; } }
请求处理和路由
此插件不会为您处理此操作,但可以使用cake的RequestHandler组件轻松将其添加到您的应用程序中,该组件支持json-api Content-Type。
例如,如果您想自动解码传入的json-api (application/vnd.api+json) 数据,您可以告诉RequestHandler自动处理它。
$this->RequestHandler->config('inputTypeMap.jsonapi', ['json_decode', true]);
也可以通过创建资源路由来实现RESTfull路由。
Router::scope('/api', function($routes) { $routes->resources('Articles', function($routes) { $routes->resources('Authors'); }); });