nickjbedford/json-response

为 PHP 7.4+ 应用定义了统一的 JSON 响应结构。

0.1.3 2023-08-25 03:08 UTC

This package is auto-updated.

Last update: 2024-09-25 05:47:07 UTC


README

PHP 的 JsonResponse 库定义了一个简单的统一结构,用于 JSON API 响应,从成功状态到错误信息和数据负载。

所有键都保证存在,即使它们是 null。这确保了 API 的客户端在检查其值之前不需要浪费时间和代码检查标准属性是否存在。

成功响应

要创建一个 成功 响应,可以使用 \YetAnother\JsonResponse::success() 方法或 json_success() 函数。

示例

$response = json_success();

$json = $response->toJSON();
$json = strval($response); // This calls $response->toJSON()

// Create a response with a payload
$personResponse = json_success([
    'id' => 123,
    'name' => 'John Citizen',
    'dob' => '1985-01-01'
]);

无数据负载的成功请求的基本响应结构如下

{
    "success": true,
    "error": null,
    "data": null
}

错误响应

要创建一个 失败 响应,可以使用 \YetAnother\JsonResponse::failure() 方法或 json_success() 函数。

示例

$response = json_failure("Person not found.", "E_NOTFOUND");

$json = $response->toJSON();

失败的请求的基本响应结构如下

{
    "success": true,
    "error": {
        "message": "Some error message...",
        "code": null,
        "data": null
    },
    "data": null
}

异常错误响应

要根据异常创建一个 失败 响应,可以使用 \YetAnother\JsonResponse::exception() 方法或 json_exception() 函数。

示例

$exception = new Exception("Database connection was lost.", "E_DBCONN");

$response = json_exception($exception, true); // true to include debugging information

$json = $response->toJSON();

响应将包含以下数据,包括异常调试数据

{
    "success": false,
    "error": {
        "message": "Database connection was lost.",
        "code": "E_DBCONN",
        "data": {
            "class": "Exception",
            "file": "/home/user/documents/my-project/example.php",
            "line": 34,
            "trace": "<stack trace...>"
        }
    }
}

如果异常响应中包含调试数据,则 error.data 属性的结构如下

记录集

要为带有分页信息的记录集响应创建标准化的响应,可以使用 \YetAnother\JsonResponse::recordSet() 方法或 json_records() 函数。

示例

$records = [ 10, 20, 30, 40, 50 ];

$response = json_records($records, 2, 5, 30, 'Integer');

$json = $response->toJSON();

响应将包含以下数据

{
    "success": true,
    "error": null,
    "data": {
        "records": [ 10, 20, 30, 40, 50 ],
        "page": 2,
        "pageLength": 5,
        "total": 30,
        "nextPage": 3,
        "previousPage": 1,
        "recordType": "Integer"
    }
}