sajadsdi/laravel-rest-response

轻松返回干净的RESTful API结构响应

1.0.4 2024-07-30 23:04 UTC

This package is auto-updated.

Last update: 2024-08-30 23:18:51 UTC


README

Laravel REST Response

Laravel REST Response

一个PHP包,简化了Laravel应用程序中RESTful API的干净且一致的响应生成。

特性

  • 版本支持:该包允许你在响应中包含API版本信息。
  • HTTP状态码:轻松设置和自定义不同响应场景的HTTP状态码。
  • 常见响应方法:预定义了创建、更新、删除、未找到、禁止、未经授权和错误请求等常见响应的方法。
  • 简单集成:无缝地将该包与你的Laravel控制器集成,以快速实现标准化的API响应。
  • 基本请求:使用BaseRequest对所有请求类进行集成,以便将验证或授权响应错误与包的响应结合。
  • CRUD操作:使用CrudApi特质提供处理CRUD操作的标准方式。

安装

你可以使用Composer安装这个库。如果你还没有为你的项目设置Composer,你可以通过遵循官方Composer安装指南来设置。

Composer安装后,运行以下命令来安装Laravel REST Response

composer require sajadsdi/laravel-rest-response

使用

建议你扩展你的基础控制器中的RestController类,以便所有继承自它的控制器都可以访问RESTful方法。这种方法为你在整个应用程序中一致地处理API响应提供了一个便捷的方式。

在基础控制器中扩展

在Laravel应用程序中,默认有一个基础控制器,你可以在以下地址找到它。

App\Http\Controllers\Controller

打开Controller.php或你的自定义基础控制器。

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;
}

你需要将BaseController更改为RestController如下。

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use SajadSdi\LaravelRestResponse\Http\Controllers\RestController;

class Controller extends RestController
{
    use AuthorizesRequests, ValidatesRequests;
}

在控制器中使用Rest方法

现在你可以在你的控制器中使用Rest方法如下。

<?php

namespace App\Http\Controllers\Banner;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Your logic here
        $data = ['key' => 'value',...];
        return $this->response($data);//you can set custom message
    }

    /**
     * Store a new resource.
     */
    public function store(Request $request)
    {
        // Your logic here
        $data = ['key' => 'value',...];
        return $this->createResponse($data,'The banner was created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function single($id)
    {
        // Your logic here
        $data = ['key' => 'value',...];
        return $this->response($data);//you can set custom message
    }

    /**
     * Update the specified resource.
     */
    public function update($id,Request $request)
    {
        // Your logic here
        $data = ['key' => 'value',...];
        //response if banner $id found and updated 
        return $this->updateResponse($data);//you can set custom message
        
        //response if banner $id not found
        return $this->notFoundResponse('banner id not found');
    }

    /**
     * Remove the specified resource.
     */
    public function destroy($id)
    {
        // Your logic here
        //response if banner $id found and deleted
        return $this->deleteResponse();
        //response if user unauthorized access
        return $this->unauthorizedResponse();//you can set custom message and errors
        //response if user forbidden access
        return $this->forbiddenResponse();//you can set custom message and errors
    }
}

自定义API版本

你可以在控制器或基础控制器中像下面这样自定义API版本。

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use SajadSdi\LaravelRestResponse\Http\Controllers\RestController;

class Controller extends RestController
{
    use AuthorizesRequests, ValidatesRequests;
    
    /**
     * Get the version of the api.
     *
     * @return string
     */
    protected function getVersion(): string
    {
        return '1.0.1';
    }
}

你还可以通过定义getVersion方法在任何控制器中自定义API版本。

实现BaseRequest

对所有请求类扩展BaseRequest以将所有响应与包的响应集成。

<?php

namespace App\Http\Requests\Auth;

use Sajadsdi\LaravelRestResponse\Http\Requests\BaseRequest;

class LoginRequest extends BaseRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        //you can set message for authorize error before return false.
        if(!is_admin){
            $this->setAuthorizeError('you cant see!');
            return false;
        }
        
        return true;
    }
    //your methods...
}

使用CRUD方法和存储库

确保你的存储库类实现了CrudRepositoryInterface。该接口必须定义创建、读取、更新、删除和索引的方法。以下是你存储库应如何看起来的一个示例

namespace App\Repositories;

use Sajadsdi\LaravelRestResponse\Contracts\CrudRepositoryInterface;

class YourModelRepository implements CrudRepositoryInterface {
    // Implement the methods
}

集成到控制器中

设置存储库后,你可以在任何控制器中使用CrudApi特质来管理你的资源。

示例

namespace App\Http\Controllers;

use Sajadsdi\LaravelRestResponse\Concerns\CrudApi;

class YourController extends Controller {
    use CrudApi;

    public function __construct(YourModelRepository $repository) {
        $this->repository = $repository;
    }
    
    // Now, you have access to createOperation, readOperation, and other methods
    // for example we implement store function with createOperation function
    public function store(YourCreateRequest $request)
    {
        return $this->createOperation($request->->validated());
    }
}

CrudApi特质为你提供了以下方法

  • createOperation($validated_data): 创建一个新的资源。
  • readOperation($validated_id): 通过其ID检索特定资源。
  • updateOperation($validated_id, $validated_data): 通过其ID更新特定资源。
  • deleteOperation($validated_id): 通过其ID删除特定资源。
  • indexOperation($search, $filter, $sort, $perPage): 检索资源列表,可选的搜索条件、过滤、排序和分页。

每个操作将自动处理成功的响应和失败(例如,错误请求或未找到错误)。

JSON响应

所有响应都是JSON格式,并且具有以下相同的数据结构。

{
    "data": [...],
    "message": "your message",
    "errors": [...],// if you set errors, otherwise an empty array.
    "status": 200,// status code
    "version": "1.0.0"//or your custom version
}

贡献

我们欢迎社区对改进和扩展此库的贡献。如果你想贡献,请遵循以下步骤

  1. 在GitHub上fork存储库。
  2. 在本地克隆你的fork。
  3. 为您的功能或错误修复创建一个新的分支。
  4. 做出您的更改,并使用清晰、简洁的提交信息提交它们。
  5. 将您的更改推送到GitHub上的分叉。
  6. 向主仓库提交拉取请求。

报告错误和安全问题

如果您在此项目中发现任何安全漏洞或错误,请通过以下渠道告诉我们

  • GitHub问题:您可以在我们的GitHub仓库中打开问题来报告错误或安全关注。请尽可能提供详细信息,包括重现问题的步骤。

  • 联系:对于敏感的安全相关问题,您可以通过以下联系渠道直接与我们联系

联系

如果您有任何问题、建议、财务问题,或者如果您想为此项目做出贡献,请随时与维护者联系

我们感谢您的反馈、支持以及任何有助于我们维护和改进此项目的财务贡献。

许可

此库是开源软件,在MIT许可证下授权。