pepperfm/api-responder-for-laravel
Composer 安装命令:
composer require pepperfm/api-responder-for-laravel
包简介
Easy api responder template using via DI
README 文档
README
Standardized API JSON responses for Laravel
Tip
Full Package Description: Helpful advice for doing things better or more easily.
Installation
composer require pepperfm/api-responder-for-laravel
Usage
Inject via Laravel DI
use Pepperfm\ApiBaseResponder\Contracts\ResponseContract; class UserController extends Controller { public function __construct(public ResponseContract $json) { } }
Direct API (config-based data key)
The simplest approach — data key and wrapping are resolved from config:
public function index(Request $request) { $users = User::query()->whereIn('id', $request->input('ids'))->get(); return $this->json->response($users->toArray()); } public function store(StoreUserRequest $request) { $user = User::create($request->validated()); return $this->json->stored($user->toArray()); } public function destroy(User $user) { $user->delete(); return $this->json->deleted(); }
Raw responses
Use raw() when you want the HTTP JSON body to be exactly your payload, without entities, meta, or message envelope fields:
public function show(User $user) { return $this->json->raw($user->toArray()); }
With Axios, this makes response.data equal to the user payload directly.
Builder API (explicit control)
Use the fluent builder when you need per-response control over data keys or wrapping:
// Explicit data key public function index() { $users = User::all(); return $this->json->withDataKey('users')->response($users->toArray()); } // REST method convention (singular key for show/update, plural for index/etc.) public function show(User $user) { return $this->json->forMethod('show')->response($user->toArray()); } // Disable wrapping (data spread into response root) public function stats() { return $this->json->build()->withoutWrapping()->response($stats); }
PHP Attributes (declarative style)
Use #[ResponseDataKey] and #[WithoutWrapping] attributes with fromAction():
use Pepperfm\ApiBaseResponder\Attributes\ResponseDataKey; use Pepperfm\ApiBaseResponder\Attributes\WithoutWrapping; #[ResponseDataKey('user')] public function show(User $user): JsonResponse { return $this->json->fromAction()->response($user->toArray()); } #[ResponseDataKey] // defaults to singular 'entity' public function edit(User $user): JsonResponse { return $this->json->fromAction()->response($user->toArray()); } #[WithoutWrapping] public function stats(): JsonResponse { return $this->json->fromAction()->response($stats); }
Pagination
public function index(Request $request) { $users = User::query()->paginate(); return $this->json->paginated($users); } // With data mapping public function index(Request $request) { $users = User::query()->paginate(); $dtoCollection = $users->getCollection()->mapInto(UserDto::class); return $this->json->paginated($dtoCollection->toArray(), $users); }
Error responses
return $this->json->error('Not found', 404); return $this->json->error('Validation failed', 422, $validator->errors());
Facades
use Pepperfm\ApiBaseResponder\Facades\BaseResponse; return BaseResponse::response($data); return BaseResponse::raw($data); return BaseResponse::forMethod('index')->response($data); return BaseResponse::fromAction()->response($data);
Method injection / resolve
public function index(Request $request, ResponseContract $json) { return $json->response($users->toArray()); } // or return resolve(ResponseContract::class)->response($users->toArray());
Paginated response format
The pagination meta is extracted automatically from LengthAwarePaginator or CursorPaginator:
export interface IPaginatedResponse<T> { current_page: number per_page: number last_page: number data: T[] from: number to: number total: number prev_page_url?: any next_page_url: string links: IPaginatedResponseLinks[] } export interface IPaginatedResponseLinks { url?: any label: string active: boolean }
Configuration
Publish the config file:
php artisan vendor:publish --provider="Pepperfm\ApiBaseResponder\Providers\ApiBaseResponderServiceProvider" --tag="config"
Key options:
plural_data_key— data key for collections (default:'entities')singular_data_key— data key for single items (default:'entity')without_wrapping— disable data-key wrapping globally (default:false)using_for_rest— enable REST method-based key resolution (default:true)methods_for_singular_key— methods that use singular key (default:['show', 'update'])force_json_response_header— auto-addAccept: application/jsonto API requests (default:true)
Check the configuration file to customize response wrapping as you prefer
Testing
composer test
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email Damon3453@yandex.ru instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
pepperfm/api-responder-for-laravel 适用场景与选型建议
pepperfm/api-responder-for-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.63k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2023 年 04 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「rest」 「api」 「response」 「laravel」 「pepperfm」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 pepperfm/api-responder-for-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 pepperfm/api-responder-for-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 pepperfm/api-responder-for-laravel 相关的其它包
同方向 / 同关键字的高下载量 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
Api bundle
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
统计信息
- 总下载量: 1.63k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 4
- 点击次数: 21
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-04-29
