hyder/json-response
Composer 安装命令:
composer require hyder/json-response
包简介
Json response handling for HTTP request.
README 文档
README
Overview
The JSON-Response package provides a simple and minimalistic interface for handling JSON responses in your Laravel applications. It offers convenient methods for returning success responses and error responses with standardized formats.
Installing
You can install the JSON-Response package via Composer. Run the following command in your terminal:
composer require hyder/json-response
Optional
The service provider will automatically get registered. Or you may manually add the service provider in your config/app.php file:
'providers' => [ // ... Hyder\JsonResponse\JsonResponseServiceProvider::class, ];
Uses
Basic Usage
To use the JSON-Response package, you need to import the JsonResponse facade and make use of its methods in your controllers or routes.
use Hyder\JsonResponse\Facades\JsonResponse; // ... public function store(Request $request) { try { // Validate the incoming request $validator = Validator::make($request->all(), [ // Validation rules ]); // Check if validation fails if ($validator->fails()) { // Return a validation error response return JsonResponse::validationError($validator->errors()); } // Process the request and create a new resource // Return a success response return JsonResponse::created($message); } catch(\Exception $ex){ return JsonResponse::internalError($ex->getMessage()); } } public function update(Request $request, $id) { // Process the request and update the specified resource // Return a success response return JsonResponse::updated($message); }
Available Success Methods
The following methods are available for returning success responses:
created($message = "Data created successfully!", $data = null)
Returns a response with a 201 Created status code, a success message, and optional data.updated($message = "Data updated successfully!", $data = null)
Returns a response with a 200 OK status code, a success message, and optional data.success($message = "Request completed successfully!")
Returns a response with a 200 OK status code and a success message.data($data, $message = "Data fetched successfully!")
Returns a response with a 200 OK status code, a success message, and the provided data.
Method Chaining
You can chain methods together for more flexibility:
// Return a success response with a custom status code and message return JsonResponse::statusCode($statusCode)->success('Your message'); // Return a success response with a custom status code, header, and message return JsonResponse::statusCode($statusCode)->withHeader($header)->success('Your message');
Please note that the statusCode() method will not affect the chaining when using the created() method.
Success Response
{
"success": true,
"message": "Your message",
"data": {
// ...
}
}
Available Error Methods
The following methods are available for returning error responses:
-
badRequest($message = "Bad request!")
Returns a response with a 400 Bad Request status code and an optional error message. This method is used to indicate a general "bad request" error. -
unauthenticated($message = 'Unauthenticated!')
Returns a response with a 401 Unauthorized status code and an optional error message. It is used to indicate that the user making the request is not authenticated. -
invalidRequest($message = 'Invalid request!')
Returns a response with a 403 Forbidden status code and an optional error message. It is used to indicate that the request is invalid or does not meet the server's expectations. -
validationError($message = 'Required field is missing!')
Returns a response with a 422 Unprocessable Entity status code and an optional error message. It is used to indicate that the request data failed validation checks. -
notFound($message = 'Not found!')
Returns a response with a 404 Not Found status code and an optional error message. It is used to indicate that the requested resource was not found. -
internalError($message = 'Internal server error!')
Returns a response with a 500 Internal Server Error status code and an optional error message. It is used to indicate that an unexpected internal server error occurred. -
error($message = 'Something went wrong!', int $statusCode = 500)
Returns a response with the specified status code and error message.
Please note that you can provide a custom error message for each error response if needed.
Feel free to adjust the method names and default error messages to better suit your application's needs.
Chaining with error method
You can chain methods together for more flexibility:
// Return a error response with a custom status code and message return JsonResponse::statusCode($statusCode)->error($message); // Return a error response with a custom status code, header, and message return JsonResponse::withHeader($header)->error($message, 400);
Please note that the statusCode() method will affect only when chaining with error() method.
Response
{
"success": false,
"message": "Your message" // Message can contain any data type
}
Customized Response
In addition to the provided methods, you can also return a customized JSON response using the response() method. This method allows you to specify the data, status code, and headers for the response.
// Return a custom response with a custom status code and data return JsonResponse::statusCode($statusCode)->response($array); // Return a custom response with a custom status code, header, and data return JsonResponse::statusCode($statusCode)->withHeader($header)->response($array);
License
This package is open-source software licensed under the MIT license.
Credits
This package is developed and maintained by Tofayel Hyder Abhi.
hyder/json-response 适用场景与选型建议
hyder/json-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 394 次下载、GitHub Stars 达 2, 最近一次更新时间为 2023 年 03 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「response」 「laravel」 「json-response」 「hyder」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hyder/json-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hyder/json-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hyder/json-response 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Easily generate a JSON response in laravel.
HTTP request logger middleware for Laravel
Class to generate a standard structure for api json responses
Alfabank REST API integration
Speed up a Laravel application by caching the entire response additions
Laravel API controller foundation for standardized JSON responses, pagination, status endpoints, trace IDs, and custom formatters.
统计信息
- 总下载量: 394
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 11
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-03-01