laurynasgadl / restponder-php
REST API 响应数据构建器
1.0.0
2020-10-29 14:04 UTC
Requires
- php: >=7.3
- ext-json: *
- psr/http-message: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9.4
This package is auto-updated.
Last update: 2024-08-29 05:19:14 UTC
README
构建更好的REST API响应。
响应示例
成功
use Luur\Restponder\Restponder; $response = Restponder::content('happy little 🌳');
{
"success":true,
"result":"happy little \ud83c\udf33",
"error":null
}
成功并附加元数据
use Luur\Restponder\Restponder; $response = Restponder::content('happy little 🌳'); $response->addMetadata('request_id', '1234-5678');
{
"success":true,
"result":"happy little \ud83c\udf33",
"error":null,
"metadata":{
"request_id":"1234-5678"
}
}
失败
use Luur\Restponder\Restponder; $response = Restponder::content(new Exception('Oops', 987));
{
"success":false,
"result":null,
"error":{
"code":987,
"message":"Oops"
}
}
失败并包含调试信息
use Luur\Restponder\Restponder; Restponder::setErrorIncludeDebug(true); $response = Restponder::content(new Exception('Oops', 987));
{
"success":false,
"result":null,
"error":{
"code":987,
"message":"Oops",
"debug":{
"type":"Exception",
"trace":"#0 ..."
}
}
}
失败并附加详细信息
use Luur\Restponder\ErrorData; use Luur\Restponder\Restponder; $handler = function (Exception $exception, ErrorData $data) { $data->addDetail('is_validation_exception', $exception instanceof ValidationException); }; Restponder::registerErrorHandler(Exception::class, $handler); $response = Restponder::content(new Exception('Oops', 987));
{
"success":false,
"result":null,
"error":{
"code":0,
"message":"Unexpected error occurred",
"details":{
"is_validation_exception":false
}
}
}
用法
响应数据
自定义对象处理器
您可以注册一个自定义对象处理器,以便能够以任何您喜欢的方式解析来自任何类型的对象的响应数据。
use Luur\Restponder\ResponseContent; use Luur\Restponder\Restponder; $handler = function (Exception $exception, ResponseContent $response) { $response->addMetadata('failed', true); $response->addMetadata('error_message', $exception->getMessage()); }; Restponder::registerResponseHandler(Exception::class, $handler);
错误数据
自定义对象处理器
您可以使用与 Response 相同的方式注册一个自定义对象处理器。
use Luur\Restponder\ErrorData; use Luur\Restponder\Restponder; $handler = function (Exception $exception, ErrorData $data) { $data->setMessage($exception->getCode().$exception->getMessage()); $data->addDetail('test', true); }; Restponder::registerErrorHandler(Exception::class, $handler);