laravelista/syndra
最新稳定版本:1.2.1
Composer 安装命令:
composer require laravelista/syndra
包简介
Common JSON responses for an API built with Laravel.
README 文档
README
Syndra is a Laravel package. It provides you with predefined JSON responses to use in your API.
Overview
When building an API you have to standardize it so that you can always expect the same response for similar requests.
When using resource controllers these methods usually are: index, store, update, destroy.
Index
For the index method you want to output data. That can be achieved with Syndra::respond($data). By default the status code is 200, but you can change it manually using Syndra::setStatusCode($statusCode)->respond($data). Syndra goes great with Fractal. To learn how to use them together read Laravel API 101.
Another thing that you will most likely want to do is to enable CORS. This can be achieved by setting the appropriate headers:
return Syndra::setHeaders([
'Access-Control-Allow-Origin' => '*',
])
->setStatusCode($statusCode)
->respond($data);
Store
In the store method you want to return that the resource was created. Syndra enables you to do this easily with Syndra::respondCreated(). This generates the following response:
{
"message": "Created",
"status_code": 201
}
You can customize the message by passing the message as a parameter Syndra::respondCreated('The resource has been created!').
Update
You can almost guess which method we use for when the resource has been updated by now; Syndra::respondUpdated(). By default this returns message Updated with status code 202. As with respondCreated, you can set the message by passing it as a parameter to respondUpdated.
Destroy
For the destroy method I like to return status code 200 with a message Ok. This can be done with Syndra::respondOk().
By applying what you have learned so far, you can now easily build your API responses however you want and they will be consistent throughout your entire API.
Advanced Usage
In this chapter I will show you how to handle most common situations which can occur in your application.
Handling Validation Errors
If you are using $this->validate($request, $rules) from your controller to validate data, you would want Syndra to return validation errors if the validation fails. To do that, go to app/Exceptions/Handler.php and in render method add this block of code:
if ($e instanceof ValidationException) { return \Syndra::respondValidationError( $e->validator->errors()->getMessages() ); }
If the validation fails, the response will be similar to the one bellow but with different messages:
{
"error" : {
"message": {
"email": [
"The email format is invalid."
]
},
"status_code": 422
}
}
Handling Model Not Found Errors
Similar to handling validation errors, model not found errors are addressed in the same way. Go to app/Exceptions/Handler.php and in render method add this block of code:
if ($e instanceof ModelNotFoundException) { return \Syndra::respondNotFound(); }
Now every time you use Model::findOrFail($id) in your controller and it does not find anything you will get this JSON response:
{
"error" : {
"message": "Not Found",
"status_code": 404
}
}
Handling Authentication & Authorization Errors
From your AuthController, if the authentication attempt fails you can return Syndra::respondUnauthorized() or if the authenticated user lacks permissions to do something you can return Syndra::respondForbidden(). Both methods accept message as the first parameter.
Hint! You can even pass an array instead of a string as a message.
Handling Server Errors
In the case that something goes terribly wrong, you can shamefully respond with Syndra::respondInternalError().
Installation
From the command line:
composer require laravelista/syndra
Include the service provider in config/app.php:
'providers' => [ ..., Laravelista\Syndra\SyndraServiceProvider::class ];
And add a facade alias to the same file at the bottom:
'aliases' => [ ..., 'Syndra' => Laravelista\Syndra\Facades\Syndra::class ];
API
There are two way of working with Syndra. As a facade Syndra::respond($data) or as a injected dependency $this->syndra->respond($data):
use Laravelista\Syndra\Syndra;
protected $syndra;
public function __construct(Syndra $syndra)
{
$this->syndra = $syndra
}
Common responses
respond
This is useful for index and show method. Use this when you want to return custom JSON output, like the one you get from Fractal.
Syndra::respond(array $data)
respondWithMessage
Use this for responding with messages. This returns a predefined message JSON template which contains the message and the status code.
Syndra::respondWithMessage($message='Ok')
Response:
{
"message": "Ok",
"status_code": 200
}
respondWithError
Use this for responding with error messages. This returns a predefined error JSON template which contains the message and the status code wrapped in error.
Syndra::respondWithError($message='Error')
Response:
{
"error": {
"message": "Error",
"status_code": 200
}
}
HTTP Status Codes 2xx
respondOk
Use this to respond with a message (200).
Syndra::respondOk($message='Ok')
respondCreated
Use this when a resource has been created (201).
Syndra::respondCreated($message='Created')
respondUpdated
Use this when a resource has been updated (202).
Syndra::respondUpdated($message='Updated')
HTTP Status Codes 4xx
respondUnauthorized
Use this when the user needs to be authorized to do something (401).
Syndra::respondUnauthorized($message='Unauthorized')
respondForbidden
Use this when the user does not have permission to do something (403).
Syndra::respondForbidden($message='Forbidden')
respondNotFound
Use this when a resource is not found (404).
Syndra::respondNotFound($message='Not Found')
respondValidationError
Use this when the validation fails (422).
Syndra::respondValidationError($message='Validation Error')
HTTP Status Codes 5xx
respondInternalError
Use this for general server errors (500).
Syndra::respondInternalError($message='Internal Error')
respondNotImplemented
Use this for HTTP not implemented errors (501).
Syndra::respondNotImplemented($message='Not Implemented')
Manipulating the status code
setStatusCode
Sets status code manually. This method can be chained (combined) with other methods.
Syndra::setStatusCode($statusCode)
Example:
Syndra::setStatusCode(200)->respond($data);
Manipulating headers
setHeaders
Sets headers on the response. This method can be chained (combined) with other methods.
Syndra::setHeaders(array $headers)
Example:
Syndra::setHeaders($headers)->respondWithMessage('Hello World!');
Credits
Many thanks to:
- @delatbabel for
notImplementedmethod and default message values
laravelista/syndra 适用场景与选型建议
laravelista/syndra 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.91k 次下载、GitHub Stars 达 26, 最近一次更新时间为 2015 年 07 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「api」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 laravelista/syndra 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 laravelista/syndra 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 laravelista/syndra 相关的其它包
同方向 / 同关键字的高下载量 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
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
Get wordpress nav menus and share the main site menus with the child sites.
统计信息
- 总下载量: 3.91k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 27
- 点击次数: 11
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-07-01