tuyakhov/yii2-json-api
Composer 安装命令:
composer require tuyakhov/yii2-json-api
包简介
Implementation of JSON API specification for the Yii framework
README 文档
README
Implementation of JSON API specification for the Yii framework
Installation
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist tuyakhov/yii2-json-api "*"
or add
"tuyakhov/yii2-json-api": "*"
to the require section of your composer.json file.
Data Serializing and Content Negotiation:
Controller:
class Controller extends \yii\rest\Controller { public $serializer = 'tuyakhov\jsonapi\Serializer'; public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'contentNegotiator' => [ 'class' => ContentNegotiator::className(), 'formats' => [ 'application/vnd.api+json' => Response::FORMAT_JSON, ], ] ]); } }
By default, the value of type is automatically pluralized.
You can change this behavior by setting tuyakhov\jsonapi\Serializer::$pluralize property:
class Controller extends \yii\rest\Controller { public $serializer = [ 'class' => 'tuyakhov\jsonapi\Serializer', 'pluralize' => false, // makes {"type": "user"}, instead of {"type": "users"} ]; }
Defining models:
- Let's define
Usermodel and declare anarticlesrelation
use tuyakhov\jsonapi\ResourceTrait; use tuyakhov\jsonapi\ResourceInterface; class User extends ActiveRecord implements ResourceInterface { use ResourceTrait; public function getArticles() { return $this->hasMany(Article::className(), ['author_id' => 'id']); } }
- Now we need to define
Articlemodel
use tuyakhov\jsonapi\ResourceTrait; use tuyakhov\jsonapi\ResourceInterface; class Article extends ActiveRecord implements ResourceInterface { use ResourceTrait; }
- As the result
Usermodel will be serialized into the proper json api resource object:
{ "data": { "type": "users", "id": "1", "attributes": { // ... this user's attributes }, "relationships": { "articles": { // ... this user's articles } } } }
Controlling JSON API output
The JSON response is generated by the tuyakhov\jsonapi\JsonApiResponseFormatter class which will
use the yii\helpers\Json helper internally. This formatter can be configured with different options like
for example the $prettyPrint option, which is useful on development for
better readable responses, or $encodeOptions to control the output
of the JSON encoding.
The formatter can be configured in the yii\web\Response::formatters property of the response application
component in the application configuration like the following:
'response' => [ // ... 'formatters' => [ \yii\web\Response::FORMAT_JSON => [ 'class' => 'tuyakhov\jsonapi\JsonApiResponseFormatter', 'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode 'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, ], ], ],
Links
Your resource classes may support HATEOAS by implementing the LinksInterface.
The interface contains getLinks() method which should return a list of links.
Typically, you should return at least the self link representing the URL to the resource object itself.
In order to appear the links in relationships getLinks() method should return self link.
Based on this link each relationship will generate self and related links.
By default it happens by appending a relationship name at the end of the self link of the primary model,
you can simply change that behavior by overwriting getRelationshipLinks() method.
For example,
class User extends ActiveRecord implements ResourceInterface, LinksInterface { use ResourceTrait; public function getLinks() { return [ Link::REL_SELF => Url::to(['user/view', 'id' => $this->id], true), ]; } }
As the result:
{ "data": { "type": "users", "id": "1", // ... this user's attributes "relationships": { "articles": { // ... article's data "links": { "self": {"href": "http://yourdomain.com/users/1/relationships/articles"}, "related": {"href": "http://yourdomain.com/users/1/articles"} } } } "links": { "self": {"href": "http://yourdomain.com/users/1"} } } }
Pagination
The page query parameter family is reserved for pagination.
This library implements a page-based strategy and allows the usage of query parameters such as page[number] and page[size]
Example: http://yourdomain.com/users?page[number]=3&page[size]=10
Enabling JSON API Input
To let the API accept input data in JSON API format, configure the [[yii\web\Request::$parsers|parsers]] property of the request application component to use the [[tuyakhov\jsonapi\JsonApiParser]] for JSON input
'request' => [ 'parsers' => [ 'application/vnd.api+json' => 'tuyakhov\jsonapi\JsonApiParser', ] ]
By default it parses a HTTP request body so that you can populate model attributes with user inputs. For example the request body:
{ "data": { "type": "users", "id": "1", "attributes": { "first-name": "Bob", "last-name": "Homster" } } }
Will be resolved into the following array:
// var_dump($_POST); [ "User" => [ "first_name" => "Bob", "last_name" => "Homster" ] ]
So you can access request body by calling \Yii::$app->request->post() and simply populate the model with input data:
$model = new User(); $model->load(\Yii::$app->request->post());
By default type users will be converted into User (singular, camelCase) which corresponds to the model's formName() method (which you may override).
You can override the JsonApiParser::formNameCallback property which refers to a callback that converts 'type' member to form name.
Also you could change the default behavior for conversion of member names to variable names ('first-name' converts into 'first_name') by setting JsonApiParser::memberNameCallback property.
Examples
Controller:
class UserController extends \yii\rest\Controller { public $serializer = 'tuyakhov\jsonapi\Serializer'; /** * @inheritdoc */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'contentNegotiator' => [ 'class' => ContentNegotiator::className(), 'formats' => [ 'application/vnd.api+json' => Response::FORMAT_JSON, ], ] ]); } /** * @inheritdoc */ public function actions() { return [ 'create' => [ 'class' => 'tuyakhov\jsonapi\actions\CreateAction', 'modelClass' => ExampleModel::className() ], 'update' => [ 'class' => 'tuyakhov\jsonapi\actions\UpdateAction', 'modelClass' => ExampleModel::className() ], 'view' => [ 'class' => 'tuyakhov\jsonapi\actions\ViewAction', 'modelClass' => ExampleModel::className(), ], 'delete' => [ 'class' => 'tuyakhov\jsonapi\actions\DeleteAction', 'modelClass' => ExampleModel::className(), ], 'view-related' => [ 'class' => 'tuyakhov\jsonapi\actions\ViewRelatedAction', 'modelClass' => ExampleModel::className() ], 'update-relationship' => [ 'class' => 'tuyakhov\jsonapi\actions\UpdateRelationshipAction', 'modelClass' => ExampleModel::className() ], 'delete-relationship' => [ 'class' => 'tuyakhov\jsonapi\actions\DeleteRelationshipAction', 'modelClass' => ExampleModel::className() ], 'options' => [ 'class' => 'yii\rest\OptionsAction', ], ]; } }
Model:
class User extends ActiveRecord implements LinksInterface, ResourceInterface { use ResourceTrait; public function getLinks() { $reflect = new \ReflectionClass($this); $controller = Inflector::camel2id($reflect->getShortName()); return [ Link::REL_SELF => Url::to(["$controller/view", 'id' => $this->getId()], true) ]; } }
Configuration file config/main.php:
return [ // ... 'components' => [ 'request' => [ 'parsers' => [ 'application/vnd.api+json' => 'tuyakhov\jsonapi\JsonApiParser', ] ], 'response' => [ 'format' => \yii\web\Response::FORMAT_JSON, 'formatters' => [ \yii\web\Response::FORMAT_JSON => 'tuyakhov\jsonapi\JsonApiResponseFormatter' ] ], 'urlManager' => [ 'rules' => [ [ 'class' => 'tuyakhov\jsonapi\UrlRule', 'controller' => ['user'], ], ] ] // ... ] // ... ]
tuyakhov/yii2-json-api 适用场景与选型建议
tuyakhov/yii2-json-api 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 118.55k 次下载、GitHub Stars 达 139, 最近一次更新时间为 2016 年 03 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「rest」 「api」 「yii2」 「json api」 「JSON-API」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 tuyakhov/yii2-json-api 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 tuyakhov/yii2-json-api 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 tuyakhov/yii2-json-api 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Kinikit - PHP Application development framework MVC component
ext-json wrapper with sane defaults
A package to cast json fields, each sub-keys is castable
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
统计信息
- 总下载量: 118.55k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 140
- 点击次数: 14
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2016-03-19