signifly/laravel-api-responder

Laravel API 的 API 响应。

v2.0.0 2023-11-21 14:26 UTC

This package is auto-updated.

Last update: 2024-09-21 16:23:42 UTC


README

Latest Version on Packagist Build Status StyleCI Quality Score Total Downloads

《signifly/laravel-api-responder》包允许您在 Laravel 应用中轻松返回 API 响应。

以下是如何使用它的一个简单示例

use Signifly\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 signifly/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 Signifly\Responder\Facades\Responder;

class ProductController
{
    public function show(Product $product)
    {
        return Responder::respond($product);
    }
}

使用特质

use Signifly\Responder\Concerns\Respondable;

class ProductController
{
    use Respondable;

    public function show(Product $product)
    {
        return $this->respond($product);
    }
}

使用服务容器

use Signifly\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@signifly.com 而不是使用问题跟踪器。

致谢

许可协议

MIT 许可协议 (MIT)。有关更多信息,请参阅 许可文件