r4nkt / laravel-api-responder
Laravel API 的 API 响应。 (从 signifly/laravel-api-responder 分支出来。)
v2.0.0
2022-06-18 12:54 UTC
Requires
- php: ^8.1
- illuminate/contracts: ^9.0
- illuminate/database: ^9.0
- illuminate/http: ^9.0
- illuminate/support: ^9.0
Requires (Dev)
- orchestra/testbench: ^7.0
- phpunit/phpunit: ^9.5
README
r4nkt/laravel-api-responder 包允许您轻松地在 Laravel 应用中返回 API 响应。
以下是如何使用它的小示例
use R4nkt\Responder\Concerns\Respondable; class ProductController extends Controller { use Respondable; public function index() { $paginator = Product::paginate(); return $this->respond($paginator); } public function store(Request $request) { $product = Product::create($request->all()); return $this->respond($product->fresh()) ->setStatusCode(201); // responds with a 201 status code } public function show(Product $product) { return $this->respond($product); } public function destroy(Product $product) { $product->delete(); return $this->respond($product); // return an empty 204 json response } }
如果存在,它将自动解析提供的数据的资源。
文档
要开始使用,请按照以下安装说明操作。
安装
您可以通过 composer 安装此包
composer require r4nkt/laravel-api-responder
包将自动注册自己。
您可以选择使用以下命令发布配置文件
php artisan vendor:publish --tag="responder-config"
这是发布配置文件的内容
return [ /* * The namespace to use when resolving resources. */ 'namespace' => 'App\\Http\\Resources', /* * Force the usage of resources. * * It will throw a ResourceNotFoundException * if it does not resolve a resource. */ 'force_resources' => false, /* * Indicates if the resources uses a naming convention with a type suffix. * * If it is set to true it will try to resolve `UserResource`. */ 'use_type_suffix' => false, ];
使用方法
响应器可以以几种方式使用。
使用外观
use R4nkt\Responder\Facades\Responder; class ProductController { public function show(Product $product) { return Responder::respond($product); } }
使用特质
use R4nkt\Responder\Concerns\Respondable; class ProductController { use Respondable; public function show(Product $product) { return $this->respond($product); } }
使用服务容器
use R4nkt\Responder\Contracts\Responder; class ProductController { public function show(Product $product, Responder $responder) { return $responder->respond($product); } }
自定义响应代码
您可以通过响应器上的 setStatusCode 方法设置响应的状态码。
return Responder::respond($data) ->setStatusCode(201);
特定的资源类
如果您想指定资源类,它可以作为响应方法的第二个参数传递
return Responder::respond($data, UserResource::class);
强制使用 API 资源
如果您想强制使用 API 资源,您必须在 config/responder.php 文件中将 force_resources 选项设置为 true。
设置为 true 时,如果找不到关联模型对应的资源,将抛出 ResourceNotFoundException。
使用类型后缀
如果您在使用类型后缀作为命名约定时创建新资源,那么您应该在 config/responder.php 文件中将 use_type_suffix 选项设置为 true。
设置为 true 时,它期望您的资源命名如下 UserResource 而不是仅仅是 User。
测试
composer test
安全
如果您发现任何安全问题,请通过电子邮件 dev@r4nkt.com 联系我们,而不是使用问题跟踪器。
鸣谢
许可
MIT 许可证 (MIT)。请参阅 许可文件 了解更多信息。