nickjbedford/laravel-endpoints

Laravel Endpoints 框架提供了一个简单的方法,用于在独立的 Responsable-style 类中实现 API 端点。

0.3.1 2023-08-14 06:43 UTC

This package is auto-updated.

Last update: 2024-09-12 07:26:25 UTC


README

Laravel Endpoints 框架提供了一个简单的方法,用于在独立的类中实现 API 端点,这些类随后会根据每个端点子类中定义的属性自动注册。

要创建一个端点,扩展 YetAnother\Laravel\Endpoint 抽象类,定义是否包含 GET、POST、UPDATE 或 DELETE 路由方法。您还必须指定路由的 URI 以及所有自动注册的路由的前缀。

Endpoint 基类提供了方便的方法,可以根据 nickjbedford/json-response-laravel 包的标准结构返回 JSON 成功、失败和异常响应。

class UsersEndpoint extends YetAnother\Laravel\Endpoint
{
    // Specify the URI of the endpoint.
    protected string $uri = '/users';
    
    // Specify the route prefix for the endpoint methods.
    // The suffixes are get, post, update and delete.
    protected string $routePrefix = 'users.';
    
    // Register the following methods when set to true.
    protected bool $get = true;
    protected bool $post = true;
    protected bool $update = true;
    protected bool $delete = true;
    
    /**
     * Override the GET method. 
     * @param Request $request
     * @return Response
     */
    function get(Request $request): Response
    {
        $users = /* fetch user(s) */;
        return $this->success($users);
    }
    
    /**
     * Override the POST method. 
     * @param Request $request
     * @return Response
     */
    function post(Request $request): Response
    {
        $user = /* create new user */;
        return $this->success($user);
    }
    
    /**
     * Override the PATCH method. 
     * @param Request $request
     * @return Response
     */
    function update(Request $request): Response
    {
        $user = /** fetch and update user */
        return $this->success(self::UpdateResponse);
    }
    
    /**
     * Override the DELETE method. 
     * @param Request $request
     * @return Response
     */
    function delete(Request $request): Response
    {
        /** fetch and delete user */
        return $this->success(self::DeleteResponse);
    }
}

注册端点

手动注册

Endpoint 基类包含 register() 方法,用于自动注册端点的路由。只需在您的端点子类实例上调用 $endpoint->register() 即可注册它们。

服务提供者注册

此包还包括 YetAnother\Laravel\EndpointServiceProvider 服务提供者类,它可以与 config/endpoints.php 配置文件一起使用。

[config/app.php]

YetAnother\Laravel\EndpointServiceProvider::class 添加到 config/app.php 配置文件中 'providers' 数组。

    // ...

    'providers' => [
        // ...
        
        YetAnother\Laravel\EndpointServiceProvider::class
    ],

    // ...

[config/endpoints.php]

在配置目录中创建一个名为 endpoints.php 的 PHP 文件,并使其返回从您的代码库中获取的端点类名数组。

    return [
        MyEndpoint::class,
        MyOtherEndpoint::class
    ];