drewlabs/laravexists

此库为基于 Laravel/Lumen 的项目提供存在性规则实现

v0.2.2 2024-01-03 12:16 UTC

This package is auto-updated.

Last update: 2024-09-21 18:01:41 UTC


README

Laravexists 包为开发者提供调用数据源上 exists 规则的实用工具和类。它内部使用 Laravel 的 Rule::exists() 或必须提供实现以检查给定数据源上数据存在性的存在性验证器类。

安装

要在 PHP 项目中安装此库,请使用 composer 包管理器

composer require drewlabs/laravexists

上述命令将安装库及其所有依赖项。

使用方法

  • 使用默认的 Laravel 存在性规则

由于库内部支持,它可以作为 Laravel 默认的 Rule::exists() 验证规则的替代品使用。

use Drewlabs\LaravExists\Exists;

//...

class MyRequest extends FormRequest {

    public function rules()
    {
        return [
            // ... validation rules
            'post_id' => [new Exists('posts', 'id')]
            // Or using the factory function
            'post_id' => [Exists::create('posts', 'id')]
        ]
    }
}
  • 使用 HTTP 存在性验证器

此库包含一个 HTTP 存在性验证器,可以作为用于验证使用 REST 接口的数据存在的工厂实例。这是此库的主要目的之一,因为它允许远程检查给定服务器上的数据是否存在。库依赖于查询参数来发送查询,以从 HTTP 服务器(如果服务器支持)过滤结果。

// Import the exist validation rule
use Drewlabs\LaravExists\Exists;
// Import the http existance client class
use Drewlabs\LaravExists\HTTPExistanceClient;

//...

class MyRequest extends FormRequest {

    public function rules()
    {
        return [
            // ... validation rules
            'post_id' => [
                Exists::create(
                    HTTPExistanceClient::create(
                        'https://:3000/api/posts',
                    )->withBearerToken($this->bearerToken()),
                    // The attribute used for check on the ressult from the HTTP server
                    'id'
                )
            ]
        ]
    }
}

注意 默认情况下,HTTPExistanceClient 类使用一个内部回调来过滤和验证服务器 JSON 响应的 data 条目。要覆盖默认实现

// Import the http existance client class
use Drewlabs\LaravExists\HTTPExistanceClient;

// ...
HTTPExistanceClient::create(
    '<RESOURCE_URL>',
    [], // Http headers
    // The response is a PHP object or array (dictionary)
    // $key is the column or key passed to the Exists construction
    // $value is the value provided by the user
    function($response, $key, $value) {
        // TODO, check if the response contains the data
        return true; // true or false base on the result of the previous step
    }
)
// ...
  • 自定义验证器

此库包含一个接口,可以实施以提供自定义的存在性验证器

use Drewlabs\LaravExists\ExistanceVerifier;

class MyCustomVerifier implements ExistanceVerifier
{
    public function exists(string $column, $value)
    {
        // TODO: Provide existance verification implementation
    }
}
  • 自定义验证错误信息(^0.1.2)

如果要自定义验证失败时向用户输出的消息,请使用 withMessage() 方法或将第三个或第四个参数传递给类构造函数

use Drewlabs\LaravExists\Exists;

// ...

class MyFormRequest
{

    public function rules()
    {
        return [
            // ...
            'post_id' => [new Exists('table', 'column', 'The selected post_id is invalid')]

            // In case using existance verifier
            'comment_id' => [new Exists(new InstanceClass, 'column', 'The selected post_id is invalid')]
        ]
    }
}

注意 由于 API 可能会更改,因此库仍在开发中。