motrack/hoodie

API响应管理包装器

1.2.1 2024-02-18 13:28 UTC

This package is auto-updated.

Last update: 2024-09-23 10:04:02 UTC


README

此包为您提供一个常规的、一致的JSON响应结构。

安装

$ composer require motrack/hoodie

Laravel版本 < 5.5

如果您不使用自动发现,请将ServiceProvider添加到config/app.php中的providers数组

Motrack\Hoodie\Providers\HoodieServiceProvider::class,

您可以将外观名称作为别名添加到config/app.php

"aliases": {
    "Hoodie" => Motrack\Hoodie\Facades\Hoodie::class
}

或者只需将外观类添加到您需要的任何地方。

use Motrack\Hoodie\Facades\Hoodie

基本用法

有两种基本方法respondSuccess()respondError()用于一般响应管理。例如,您可以使用Hoodie轻松地在Controller中创建响应

    public function doFunction(): JsonResponse
    {
        ...
        return Hoodie::respondSuccess();
    }

还有自定义响应消息、状态码甚至设置一些自定义头部的选项。

return Hoodie::respondSuccess('Success!', 200, ['token' => $token, 'platform' => 'core']);

您甚至可以通过respondError()方法传递异常来管理在您的.env文件中将APP_DEBUG设置为true时的响应错误,如果您愿意的话。

return Hoodie::respondError('Something went wrong!', 500, $exception, $headers );

高级用法

如果您想通过API响应的结果传递您使用的资源,可以调用respondWithResource()方法。

use App\Http\Resources\PostResource; // the Json Resource you've provided for the result

class PostController extends Controller
{
    ...
    public function show(Post $post): JsonResponse
    {
        return Hoodie::respondWithResource(new PostResource($post) , 'Post Created Successfully', 201 , ['my_custom_header' => 'header_value']);
    }
    ...
}

respondWithResourceCollection()方法用于当您需要通过API的结果传递JSON集合资源时。

use App\Http\Resources\PostCollection; // the Json Collection you've provided for the result

class PostController extends Controller
{
    public function index(): JsonResponse
    {
        return Hoodie::respondWithResourceCollection(new PostCollection(Post::paginate()) , 'List of Posts Retrieved Successfully', 200 , ['my_custom_header' => 'header_value']);
    }
    ...
}