egeatech / laravel-responses
一个简单的包,用于更好地处理应用响应。
4.0.1
2024-01-09 16:46 UTC
Requires
- php: ^8.0
- egeatech/laravel-exceptions: ^3.0.1
- illuminate/support: ^6|^7|^8|^9|^10
Requires (Dev)
- orchestra/testbench: ~5|~6|~7|~8
- phpunit/phpunit: ~9.0
This package is auto-updated.
Last update: 2024-09-09 18:14:38 UTC
README
提供一些标准化响应类的包。
安装
此包支持 Laravel 6、7、8 和 9,但要求至少 PHP 8.0。PHP 7.4 在 2.1.1 版本中受支持。
通过 Composer
$ composer require egeatech/laravel-responses
使用方法
只需从您的控制器方法返回 ApiResponse
或 PaginatedApiResponse
的新实例。
这两个类具有相似的构造函数签名
以下是 ApiResponse
的构造函数
public function __construct( # Either null, a valid Eloquent model or an \Illuminate\Support\Collection instance or a generic payload mixed $responseData, # A classFQN extending Laravel JsonResource instance, to be used to know how to map response data. Can be null if data don't need formatting. ?string $responseFormatter, # A valid HTTP status code, to be returned to the caller int $httpStatus = \Illuminate\Http\JsonResponse::HTTP_OK, # An optional ApplicationException instance, to properly provide a valid error message representation ?\EgeaTech\LaravelExceptions\Interfaces\Exceptions\LogicErrorException $logicException = null ) {}
以下是 PaginatedApiResponse
类的构造函数
public function __construct( # A standard Laravel paginator instance, holding both data and pagination information \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginatorData, # A classFQN extending Laravel JsonResource instance, to be used to know how to map response data string $responseFormatter, # A valid HTTP status code, to be returned to the caller int $httpStatus = \Illuminate\Http\JsonResponse::HTTP_OK, # An optional ApplicationException instance, to properly provide a valid error message representation ?\EgeaTech\LaravelExceptions\Interfaces\Exceptions\LogicErrorException $logicException = null ) {}
ApiResponse
类的一个示例用法如下
<?php namespace App\Http\Controllers\Api\TestController; use App\Http\Controllers\Controller; use App\Http\Requests\ModelUpdateRequest; use EgeaTech\LaravelResponses\Http\Responses\ApiResponse; use EgeaTech\LaravelExceptions\Interfaces\Exceptions\LogicErrorException; class TestController extends Controller { public function __invoke(ModelUpdateRequest $request): ApiResponse { $occurredException = null; $databaseModel = null; try { $modelData = $request->validated(); $databaseModel = $this->updateModel($modelData); } catch (LogicErrorException $exception) { $occurredException = $exception; } return new ApiResponse( $databaseModel, DatabaseModelResource::class, $occurredException ? $occurredException->getCode() : ApiResponse::HTTP_ACCEPTED, $occurredException ); } }
对于其他类,只要您提供第一个参数为 LenghtAwarePaginator
实例,其用法相同。
变更日志
请参阅 CHANGELOG 了解最近更改的详细信息。
贡献
请参阅 CONTRIBUTING 了解详细信息。
安全
如果您发现任何安全相关的问题,请通过电子邮件联系作者,而不是使用问题跟踪器。
鸣谢
许可证
软件许可协议为 MIT。有关更多信息,请参阅 LICENSE 文件。