后代/laravel-handle-responder

用于构建API响应的Laravel包

2.8 2020-03-26 03:15 UTC

This package is auto-updated.

Last update: 2024-09-06 21:03:23 UTC


README

Laravel Responder是一个用于构建API响应的包,

安装

要开始使用,请通过Composer安装此包

composer require offspring/laravel-handle-responder

发布包资源 (可选)

您还可以使用vendor:publish Artisan命令发布包配置和语言文件

php artisan vendor:publish --provider="Offspring\Responder\ResponderServiceProvider"

这将发布一个位于config文件夹中的responder.php配置文件。它还会在您的lang/en文件夹内发布一个errors.php文件,该文件可以用于存储错误消息。


####  Use `responder` Helper

If you're a fan of Laravel's `response` helper function, you may like the `responder` helper function:

```php
return responder()->success();
return responder()->error();

构建响应

successerror方法分别返回一个SuccessResponseBuilderErrorResponseBuilder,它们都扩展了一个抽象的ResponseBuilder,这赋予它们共同的行为。当从控制器返回时,它们将被转换为JSON,但您可以使用respond方法显式创建一个Illuminate\Http\JsonResponse实例。

return responder()->success()->respond();
return responder()->error()->respond();

默认情况下,状态码设置为200,但可以通过设置第一个参数来更改。您还可以将一系列头部作为第二个参数传递。

return responder()->success()->respond(201, ['x-foo' => true]);
return responder()->error()->respond(404, ['x-foo' => false]);

出于一致性的考虑,始终使用respond方法。

响应数据类型转换

除了使用respond方法将响应转换为JsonResponse之外,您还可以将响应数据转换为数组等其他类型。

return responder()->success()->toArray();
return responder()->error()->toArray();

响应装饰

响应装饰器允许在响应返回之前进行最后的修改。该包自带两个响应装饰器,默认添加了statussuccess字段到响应输出。配置文件中的decorators键定义了所有启用的响应装饰器的列表。

'decorators' => [
    \Offspring\Responder\Http\Responses\Decorators\StatusCodeDecorator::class,
    \Offspring\Responder\Http\Responses\Decorators\SuccessFlagDecorator::class,
],

您可以通过从列表中删除装饰器来禁用它,或者通过扩展抽象类Flugg\Responder\Http\Responses\Decorators\ResponseDecorator添加自己的装饰器。您还可以为每个响应添加额外的装饰器。

return responder()->success()->decorator(ExampleDecorator::class)->respond();
return responder()->error()->decorator(ExampleDecorator::class)->respond();

该包还附带了一些默认禁用的情境装饰器,但可以将它们添加到装饰器列表中。

  • PrettyPrintDecorator装饰器将美化JSON输出;
\Offspring\Responder\Http\Responses\Decorators\PrettyPrintDecorator::class,
  • EscapeHtmlDecorator装饰器基于“清理输入,转义输出”的概念,将在API返回的所有字符串中转义HTML实体。您可以安全地存储输入数据“原样”(即使是恶意HTML标签),并确信它们将以无害的字符串输出。请注意,使用此装饰器,将数据作为文本打印将导致错误表示,您必须将其作为HTML打印才能检索原始值。
\Offspring\Responder\Http\Responses\Decorators\EscapeHtmlDecorator::class,