philiprehberger/php-api-response 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/php-api-response

Composer 安装命令:

composer require philiprehberger/php-api-response

包简介

Standardized API response builder for consistent JSON APIs

README 文档

README

Tests Latest Version on Packagist Last updated

Standardized API response builder for consistent JSON APIs.

Requirements

  • PHP 8.2+

Installation

composer require philiprehberger/php-api-response

Usage

Success Responses

use PhilipRehberger\ApiResponse\ApiResponse;

// Basic success
$response = ApiResponse::success();
// {"success": true, "message": "OK", "data": null}

// Success with data
$response = ApiResponse::success(['id' => 1, 'name' => 'John']);
// {"success": true, "message": "OK", "data": {"id": 1, "name": "John"}}

// Created
$response = ApiResponse::created(['id' => 42]);
// {"success": true, "message": "Created", "data": {"id": 42}}

// No content
$response = ApiResponse::noContent();

// Accepted (202) — request queued for async processing
$response = ApiResponse::accepted(['job_id' => 'abc-123']);
// {"success": true, "message": "Accepted", "data": {"job_id": "abc-123"}}
// {"success": true, "message": "No Content", "data": null}

Error Responses

// Generic error
$response = ApiResponse::error('Something went wrong', 500);
// {"success": false, "message": "Something went wrong", "data": null}

// Not found
$response = ApiResponse::notFound('User not found');
// {"success": false, "message": "User not found", "data": null}

// Unauthorized (401)
$response = ApiResponse::unauthorized('Token expired');

// Forbidden (403)
$response = ApiResponse::forbidden('Insufficient permissions');

// Internal server error (500)
$response = ApiResponse::internalServerError('Database unavailable');

// Validation error
$response = ApiResponse::validationError([
    'email' => ['The email field is required.'],
    'name' => ['The name must be at least 2 characters.'],
]);
// {"success": false, "message": "Validation failed", "data": null, "errors": {"email": [...], "name": [...]}}

Paginated Responses

$response = ApiResponse::paginated(
    items: $users,
    total: 150,
    page: 2,
    perPage: 25,
);
// {"success": true, "message": "OK", "data": [...], "meta": {"pagination": {"total": 150, "page": 2, "per_page": 25, "last_page": 6}}}

Serialization

ResponsePayload implements JsonSerializable and Stringable:

$response = ApiResponse::success(['key' => 'value']);

// Convert to array
$array = $response->toArray();

// Convert to JSON string
$json = $response->toJson();
$json = $response->toJson(JSON_PRETTY_PRINT);

// Use with json_encode directly
$json = json_encode($response);

// Cast to string
$string = (string) $response;

Using with Laravel

Return responses directly from controllers by accessing the payload properties:

public function index(): JsonResponse
{
    $users = User::paginate(25);

    $payload = ApiResponse::paginated(
        items: $users->items(),
        total: $users->total(),
        page: $users->currentPage(),
        perPage: $users->perPage(),
    );

    return response()->json($payload->toArray(), $payload->statusCode);
}

Fluent Chaining

All with* methods return a new ResponsePayload instance, keeping the original unchanged:

$response = ApiResponse::success(['id' => 1, 'name' => 'John'])
    ->withMeta(['request_id' => 'abc-123', 'version' => '2.0'])
    ->withHeaders(['X-Request-Id' => 'abc-123'])
    ->withStatusCode(202);

// Merge additional metadata onto a paginated response
$response = ApiResponse::paginated($users, total: 150, page: 2, perPage: 25)
    ->withMeta(['cache' => 'hit']);

// Attach pagination to any success response after the fact
$response = ApiResponse::success($users)
    ->withPagination(total: 150, page: 2, perPage: 25);

// Attach headers for use in your framework's response
$payload = ApiResponse::created(['id' => 42])
    ->withHeaders(['Location' => '/users/42']);

return response()->json($payload->toArray(), $payload->statusCode)
    ->withHeaders($payload->headers);

Response Shape

All responses follow a consistent structure:

{
    "success": true,
    "message": "OK",
    "data": null,
    "errors": {},
    "meta": {}
}
  • success (bool) - Always present
  • message (string) - Always present
  • data (mixed) - Always present
  • errors (object) - Only present when there are errors
  • meta (object) - Only present when metadata is provided (e.g., pagination)

API

Method Status Code Description
ApiResponse::success($data, $message) 200 Successful response with optional data
ApiResponse::created($data, $message) 201 Resource created successfully
ApiResponse::noContent($message) 204 Success with no response body
ApiResponse::error($message, $statusCode, $errors) 400 Generic error response
ApiResponse::validationError($errors, $message) 422 Validation failure with field errors
ApiResponse::notFound($message) 404 Resource not found
ApiResponse::unauthorized($message, $errors) 401 Authentication required or failed
ApiResponse::forbidden($message, $errors) 403 Authenticated but not permitted
ApiResponse::accepted($data, $message) 202 Request accepted for asynchronous processing
ApiResponse::internalServerError($message, $errors) 500 Unexpected server-side failure
ApiResponse::paginated($items, $total, $page, $perPage) 200 Paginated list with metadata

Fluent Methods on ResponsePayload

Method Description
withMeta(array $meta) Returns a new instance with merged metadata
withHeaders(array $headers) Returns a new instance with custom response headers
withStatusCode(int $code) Returns a new instance with overridden HTTP status code
withPagination(int $total, int $page, int $perPage) Returns a new instance with a pagination block merged into meta

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/php-api-response 适用场景与选型建议

philiprehberger/php-api-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「rest」 「api」 「response」 「standardized」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/php-api-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/php-api-response 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/php-api-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 58
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 16
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-13