olegstan/laravel-rest

为Laravel框架提供强大的REST功能。

1.1.53 2023-05-10 12:31 UTC

This package is auto-updated.

Last update: 2024-09-23 08:28:47 UTC


README

概览

olegstan/laravel-rest 包提供了一种简洁的方法来构建Laravel的RESTful API,强调约定优于配置。它自动设置API路由并组织应用程序结构,以增强REST API的开发。本文档将引导您了解如何安装、设置和基本使用此包。

安装

首先通过Composer安装包

composer require olegstan/laravel-rest

此命令将 olegstan/laravel-rest 包添加到您的项目中,启用其功能和功能。

相关包

为了最佳使用 olegstan/laravel-rest,请安装相关的 laravel-request 包,该包通过处理请求验证等功能补充主包。可在以下位置找到它:

https://github.com/olegstan/laravel-request

配置

安装后,发布包的资源和配置到您的项目

php artisan vendor:publish --provider="LaravelRest\LaravelRestServiceProvider"

此命令将必要的文件复制到您的项目中,为API的结构和行为设置场景。

自动API路由

包发布后,API路由将自动配置。路由约定遵循以下模式

/api/v1/call/{controllerName}/{functionName}

此模式便于通过API端点直接访问控制器方法。例如,要访问 ClientController 中的 postStore 方法,您将使用

  • URL: /api/v1/call/client/store
  • 方法: POST

项目结构

该包按照有利于API开发的方式组织您的Laravel项目,如下所示

/App
    /Api
        /Controllers
            /Common - Controllers without authentication requirements
            /AnyRole - Controllers for specific role-based access
        /Helpers - Utility functions and classes
        /Requests - Custom request validation classes
        /Transformers
            /Base - Common data transformers
            /AnyRole - Role-specific data transformers

控制器和请求

控制器使用 StartRequestInterface 来处理请求,确保在您的应用程序中采用标准的请求处理方法。

请求处理示例

const form = new FormData();
form.append('user_id', 10);
form.append('first_name', 'Andrey');
form.append('last_name', 'Kirov');

const requestOptions = {
  method: "POST",
  body: form
};

let url = SERVER_API + '/api/v1/call/client/store';

await fetch(url, requestOptions)
  .then(response => response.json())
  .then(json => { /* Handle the JSON response */ })
  .catch(error => { /* Handle errors */ });

在控制器中处理数据

发送到端点(如上面的示例)的数据很容易在控制器中检索

class ClientController extends BaseController
{
    public function postStore(Request $request)
    {
        $userId = $request->input('user_id');
        $firstName = $request->input('first_name');
        $lastName = $request->input('last_name');

        // Implement your logic here

        return $this->response()->success();
    }
}

支持

有关 olegstan/laravel-rest 包的疑问或进一步的帮助,请联系 olegstan@inbox.ru