nilportugues/laravel5-jsend
Composer 安装命令:
composer require nilportugues/laravel5-jsend
包简介
Laravel 5 JSend API Transformer Package
README 文档
README
Compatible with Laravel 5.0, 5.1 & 5.2
Installation
Use Composer to install the package:
$ composer require nilportugues/laravel5-jsend
Laravel 5 / Lumen Configuration
Step 1: Add the Service Provider
Laravel
Open up config/app.php and add the following line under providers array:
'providers' => [ //... \NilPortugues\Laravel5\JSend\Laravel5JSendServiceProvider::class, ],
Lumen
Open up bootstrap/app.phpand add the following lines before the return $app; statement:
$app->register(\NilPortugues\Laravel5\JSend\Laravel5JSendServiceProvider::class); $app->configure('jsend');
Also, enable Facades by uncommenting:
$app->withFacades();
Step 2: Add the mapping
Create a jsend.php file in config/ directory. This file should return an array returning all the class mappings.
Step 3: Usage
For instance, lets say the following object has been fetched from a Repository , lets say PostRepository - this being implemented in Eloquent or whatever your flavour is:
use Acme\Domain\Dummy\Post; use Acme\Domain\Dummy\ValueObject\PostId; use Acme\Domain\Dummy\User; use Acme\Domain\Dummy\ValueObject\UserId; use Acme\Domain\Dummy\Comment; use Acme\Domain\Dummy\ValueObject\CommentId; //$postId = 9; //PostRepository::findById($postId); $post = new Post( new PostId(9), 'Hello World', 'Your first post', new User( new UserId(1), 'Post Author' ), [ new Comment( new CommentId(1000), 'Have no fear, sers, your king is safe.', new User(new UserId(2), 'Barristan Selmy'), [ 'created_at' => (new \DateTime('2015/07/18 12:13:00'))->format('c'), 'accepted_at' => (new \DateTime('2015/07/19 00:00:00'))->format('c'), ] ), ] );
And a series of mappings, placed in config/jsend.php, that require to use named routes so we can use the route() helper function:
<?php //config/jsend.php return [ [ 'class' => 'Acme\Domain\Dummy\Post', 'alias' => 'Message', 'aliased_properties' => [ 'author' => 'author', 'title' => 'headline', 'content' => 'body', ], 'hide_properties' => [ ], 'id_properties' => [ 'postId', ], 'urls' => [ 'self' => ['name' => 'get_post'], //named route 'comments' => ['name' => 'get_post_comments'], //named route ], ], [ 'class' => 'Acme\Domain\Dummy\ValueObject\PostId', 'alias' => '', 'aliased_properties' => [], 'hide_properties' => [], 'id_properties' => [ 'postId', ], 'urls' => [ 'self' => ['name' => 'get_post'], //named route ], ], [ 'class' => 'Acme\Domain\Dummy\User', 'alias' => '', 'aliased_properties' => [], 'hide_properties' => [], 'id_properties' => [ 'userId', ], 'urls' => [ 'self' => ['name' => 'get_user'], //named route 'friends' => ['name' => 'get_user_friends'], //named route 'comments' => ['name' => 'get_user_comments'], //named route ], ], [ 'class' => 'Acme\Domain\Dummy\ValueObject\UserId', 'alias' => '', 'aliased_properties' => [], 'hide_properties' => [], 'id_properties' => [ 'userId', ], 'urls' => [ 'self' => ['name' => 'get_user'], //named route 'friends' => ['name' => 'get_user_friends'], //named route 'comments' => ['name' => 'get_user_comments'], //named route ], ], [ 'class' => 'Acme\Domain\Dummy\Comment', 'alias' => '', 'aliased_properties' => [], 'hide_properties' => [], 'id_properties' => [ 'commentId', ], 'urls' => [ 'self' => ['name' => 'get_comment'], //named route ], ], [ 'class' => 'Acme\Domain\Dummy\ValueObject\CommentId', 'alias' => '', 'aliased_properties' => [], 'hide_properties' => [], 'id_properties' => [ 'commentId', ], 'urls' => [ 'self' => ['name' => get_comment'], //named route ], ], ];
The named routes belong to the app/Http/routes.php. Here's a sample for the routes provided mapping:
Laravel
Route::get( '/post/{postId}', ['as' => 'get_post', 'uses' => 'PostController@getPostAction'] ); Route::get( '/post/{postId}/comments', ['as' => 'get_post_comments', 'uses' => 'CommentsController@getPostCommentsAction'] ); //...
Lumen
$app->get( '/post/{postId}', ['as' => 'get_post', 'uses' => 'PostController@getPostAction'] ); $app->get( '/post/{postId}/comments', ['as' => 'get_post_comments', 'uses' => 'CommentsController@getPostCommentsAction'] ); //...
All of this set up allows you to easily use the JSendSerializer service as follows:
<?php namespace App\Http\Controllers; use Acme\Domain\Dummy\PostRepository; use NilPortugues\Laravel5\JSend\JSendSerializer; use NilPortugues\Laravel5\JSend\JSendResponseTrait; class PostController extends \Laravel\Lumen\Routing\Controller { use JSendResponseTrait; /** * @var PostRepository */ private $postRepository; /** * @var JSendSerializer */ private $serializer; /** * @param PostRepository $postRepository * @param JSendSerializer $jSendSerializer */ public function __construct(PostRepository $postRepository, JSendSerializer $jSendSerializer) { $this->postRepository = $postRepository; $this->serializer = $jSendSerializer; } /** * @param int $postId * * @return \Symfony\Component\HttpFoundation\Response */ public function getPostAction($postId) { $post = $this->postRepository->findById($postId); /** @var \NilPortugues\Api\JSend\JSendTransformer $transformer */ $transformer = $this->serializer->getTransformer(); $transformer->setSelfUrl(route('get_post', ['postId' => $postId])); $transformer->setNextUrl(route('get_post', ['postId' => $postId+1])); return $this->response($this->serializer->serialize($post)); } }
Output:
HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/json; charset=utf-8
{
"status": "success",
"data": {
"post_id": 9,
"title": "Hello World",
"content": "Your first post",
"author": {
"user_id": 1,
"name": "Post Author"
},
"comments": [
{
"comment_id": 1000,
"dates": {
"created_at": "2015-07-18T12:13:00+00:00",
"accepted_at": "2015-07-19T00:00:00+00:00"
},
"comment": "Have no fear, sers, your king is safe.",
"user": {
"user_id": 2,
"name": "Barristan Selmy"
}
}
]
},
"links": {
"self": {
"href": "http://example.com/post/9"
},
"next": {
"href": "http://example.com/post/10"
}
}
}
Response objects (JSendResponseTrait)
The following JSendResponseTrait methods are provided to return the right headers and HTTP status codes are available:
private function errorResponse($message, $code = 500, $data = null); private function failResponse($json); private function response($json);
## Quality
To run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.
This library attempts to comply with PSR-1, PSR-2, PSR-4 and PSR-7.
If you notice compliance oversights, please send a patch via Pull Request.
## Contribute
Contributions to the package are always welcome!
- Report any bugs or issues you find on the issue tracker.
- You can grab the source code at the package's Git repository.
## Support
Get in touch with me using one of the following means:
- Emailing me at contact@nilportugues.com
- Opening an Issue
- Using Gitter:
## Authors
License
The code base is licensed under the MIT license.
nilportugues/laravel5-jsend 适用场景与选型建议
nilportugues/laravel5-jsend 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 429 次下载、GitHub Stars 达 5, 最近一次更新时间为 2015 年 08 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「api」 「response」 「serializer」 「laravel」 「transformer」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 nilportugues/laravel5-jsend 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 nilportugues/laravel5-jsend 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nilportugues/laravel5-jsend 相关的其它包
同方向 / 同关键字的高下载量 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
HTTP request logger middleware for Laravel
A PSR-7 compatible library for making CRUD API endpoints
Class to generate a standard structure for api json responses
统计信息
- 总下载量: 429
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 5
- 点击次数: 24
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-08-18