kevupton/laravel-json-response
Composer 安装命令:
composer require kevupton/laravel-json-response
包简介
Easy Json responses for laravel
README 文档
README
An Ethereal Package
Easy way to implement API formatted json responses.
Format:
{
"data": {...},
"errors": [],
"success": true,
"status_code": 200,
"token": null
}
Setup
Install:
composer require kevupton/laravel-json-response
Add the service provider to your app config:
\Kevupton\LaravelJsonResponse\Providers\LaravelJsonResponseProvider::class,
Add the middleware to your app\Http\Kernel.php
Either:
// Formats all responses in json. Catches errors listed in config and JsonResponseErrorExceptions Kevupton\LaravelJsonResponse\Middleware\OutputJsonResponse, // Extends the OutputJsonResponse to catch all errors, to keep the JSON output Kevupton\LaravelJsonResponse\Middleware\CatchAllExceptions,
Config
Publish the config by using the command:
php artisan vendor:publish
Examples
Example returning the data
Usage:
Route::get('test', function () { return ['hello' => true]; });
Output:
{
"data": {
"hello": true
},
"errors": [],
"success": true,
"status_code": 200
}
Example manipulating the JSON directly
You can also set data and tokens directly from this method.
Usage:
Route::get('test', function () { json_response()->error('This an example error message') ->setStatusCode(\Illuminate\Http\Response::HTTP_BAD_REQUEST); });
Output:
{
"data": [],
"errors": [
"This an example error message"
],
"success": false,
"status_code": 400
}
Example returning a model
Models are added onto the data using snake_case.
Usage:
Route::get('test', function () { return \App\Models\TestModel::find(2); });
Output:
{
"data": {
"test_model": {
"id": 2
}
},
"success": false,
"status_code": 400
}
Example returning an Arrayable
Arrayable objects have toArray methods, which are merged with the data.
Usage:
Route::get('test', function () { return \App\Models\TestModel::paginate(); });
Output:
{
"data": {
"current_page": 1,
"data": [
{
"id": 1
},
{
"id": 2
},
...
],
"first_page_url": "http://url/api/test?page=1",
"from": 1,
"last_page": 3,
"last_page_url": "http://url/api/test?page=3",
"next_page_url": "http://url/api/test?page=2",
"path": "http://url/api/test",
"per_page": 10,
"prev_page_url": null,
"to": 10,
"total": 24
},
"errors": [],
"success": true,
"status_code": 200
}
Example with validation errors
Usage:
Route::get('test', function () { throw new \Illuminate\Validation\ValidationException(\Validator::make([], ['test' => 'required'])); });
Output:
{
"data": [],
"errors": {
"test": [
"The test field is required."
]
},
"success": false,
"status_code": 422
}
Example Exception
NOTE: APP_DEBUG=true will display a stack trace
Usage:
Route::get('test', function () { throw new Exception('test'); });
Output:
{
"data": [],
"errors": [
"test message",
{
"file": "C:\\Users\\kevin\\Projects\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Route.php",
"line": 172,
"function": "runCallable",
"class": "Illuminate\\Routing\\Route",
"type": "->",
"args": []
},
{...},
{...},
{...},
{...},
...
],
"success": false,
"status_code": 500
}
Exception Handling
Exceptions can be caught by using the config file:
<?php use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\Response; use Illuminate\Validation\ValidationException; use Kevupton\LaravelJsonResponse\JsonResponse; return [ 'exceptions' => [ /** * Show model not found when receiving this error */ ModelNotFoundException::class => 'Model not found', // OR ModelNotFoundException::class => ['NOT_FOUND', 'Model not found'], // OR ModelNotFoundException::class => [ 'error' => 'Model not found', // these are functions on the JsonResponse, being dynamically invoked 'setStatusCode' => Response::HTTP_NOT_FOUND ], /** * Add all the errors from the validation and continue */ ValidationException::class => function (ValidationException $e, JsonResponse $json) { $json ->mergeErrors($e->errors()) ->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY); } ] ];
kevupton/laravel-json-response 适用场景与选型建议
kevupton/laravel-json-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.61k 次下载、GitHub Stars 达 16, 最近一次更新时间为 2017 年 11 月 28 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「laravel」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 kevupton/laravel-json-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 kevupton/laravel-json-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 kevupton/laravel-json-response 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Kinikit - PHP Application development framework MVC component
A Laravel Eloquent model trait for translatable resource
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
ext-json wrapper with sane defaults
Help to manage meta data on Laravel Eloquent model
A package to cast json fields, each sub-keys is castable
统计信息
- 总下载量: 1.61k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 16
- 点击次数: 26
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2017-11-28