为 Laravel 定制的表单请求和服务验证

该软件包的规范仓库似乎已丢失,因此该软件包已被冻结。

0.2.3 2019-09-09 14:28 UTC

This package is auto-updated.

Last update: 2022-05-09 20:27:53 UTC


README

Laravel 的自定义表单请求

Latest Stable Version Build Status Quality Score Total Downloads

Perfect Oblivion

免责声明

PerfectOblivion 命名空间下的软件包旨在提供一些我更喜欢不从头开始在每个项目中复制的基功能。这里没有什么突破性的。

软件包目标

表单请求

  • Laravel 提供了有限的清理选项,通过默认的中间件。例如,默认启用了TrimStrings 中间件。但是,您需要负责执行对用户数据的任何其他清理。 waavi/sanitizer 使这变得轻而易举。在表单请求中,它的工作方式类似于验证。同样,“规则”方法返回一个规则数组,而“过滤器”方法应返回一个过滤器数组。默认情况下,已将此方法添加到您的 perfect-oblivion/valid FormRequest 类中。在这里,就像“规则”方法一样,返回您要在数据上运行的过滤器数组。请参阅可用的过滤器 这里,您可以直接使用。您还可以创建自己的 自定义过滤器 来使用。

自定义规则

我经常在 Laravel 中使用自定义规则。有时候,我想要在自定义规则中访问当前的 FormRequest 和/或当前的验证器。可以通过自定义规则构造函数传递任何内容,但是,传递 FormRequest、Validator 以及其他数据的方式可能会很丑陋。请参见以下内容

    public function rules()
    {
        return [
            'name' => ['required', 'size:2', new NotSpamRule($this, $this->getValidator())],
        ];
    }

使用此软件包,以下将完成相同的事情

    public function rules()
    {
        return [
            'name' => ['required', 'size:2', new NotSpamRule],
        ];
    }

这可能看起来改进不大,但我更喜欢我的规则尽可能干净和易读。

这些自定义规则可以在您的表单请求或验证服务类中使用。请参阅以下内容。

ValidationService

在我的日常开发中,我使用类似 Paul JonesADR 模式。使用此模式,不建议在“控制器”级别进行验证。这是域的功能。建议尽快执行任何授权(我更喜欢通过中间件使用 Laravel 的内置 Gates/Policies 进行授权)。然后可以从请求中检索数据并将其传递到服务中进行进一步的数据检索、操作等。这是域层的一部分。使用 ValidationService,您可以在服务开始处理数据之前验证数据。

ValidationService服务大量借鉴了Laravel的表单请求,并以类似的方式运行,但没有使用授权组件。更多内容请参考下面的“使用”部分。

安装

您可以通过Composer安装此包。在您的项目目录中,在终端中输入

composer require perfect-oblivion/valid

在Laravel > 5.6.0版本中,ServiceProvider将自动检测并注册。如果您使用的是Laravel的旧版本,请将包的ServiceProvider添加到您的config/app.php文件中的'providers'数组中

'providers' => [
    //...
    PerfectOblivion\Valid\ValidServiceProvider::class,
    //...
];

然后,如果您想更改任何配置选项,运行

php artisan vendor:publish

并选择PerfectOblivion/Valid选项。

这将复制包配置(valid.php)到您的'config'文件夹中。在这里,您可以设置FormRequests的命名空间和后缀,ServiceValidation类和自定义规则

<?php

return [
    'requests' => [
        /*
        |--------------------------------------------------------------------------
        | Namespace
        |--------------------------------------------------------------------------
        |
        | Set the namespace for the Custom Form Requests.
        |
        */
        'namespace' => 'Http\\Requests',

        /*
        |--------------------------------------------------------------------------
        | Suffix
        |--------------------------------------------------------------------------
        |
        | Set the suffix to be used when generating Custom Form Requests.
        |
        */
        'suffix' => 'Request',

        /*
        |--------------------------------------------------------------------------
        | Duplicate Suffixes
        |--------------------------------------------------------------------------
        |
        | If you have a Request suffix set and try to generate a Request that also includes the suffix,
        | the package will recognize this duplication and rename the Request to remove the suffix.
        | This is the default behavior. To override and allow the duplication, change to false.
        |
        */
        'override_duplicate_suffix' => true,
    ],
    'rules' => [
        /*
        |--------------------------------------------------------------------------
        | Namespace
        |--------------------------------------------------------------------------
        |
        | Set the namespace for the custom rules.
        |
     */
        'namespace' => 'Rules',

        /*
        |--------------------------------------------------------------------------
        | Suffix
        |--------------------------------------------------------------------------
        |
        | Set the suffix to be used when generating custom rules.
        |
         */
        'suffix' => 'Rule',

        /*
        |--------------------------------------------------------------------------
        | Duplicate Suffixes
        |--------------------------------------------------------------------------
        |
        | If you have a Rule suffix set and try to generate a Rule that also includes the suffix,
        | the package will recognize this duplication and rename the Rule to remove the suffix.
        | This is the default behavior. To override and allow the duplication, change to false.
        |
        */
        'override_duplicate_suffix' => true,
    ],
    'validation-services' => [
        /*
        |--------------------------------------------------------------------------
        | Namespace
        |--------------------------------------------------------------------------
        |
        | Set the namespace for the validation services.
        |
     */
        'namespace' => 'Services',

        /*
        |--------------------------------------------------------------------------
        | Suffix
        |--------------------------------------------------------------------------
        |
        | Set the suffix to be used when generating validation services.
        |
         */
        'suffix' => 'Validation',

        /*
        |--------------------------------------------------------------------------
        | Duplicate Suffixes
        |--------------------------------------------------------------------------
        |
        | If you have a Validation suffix set and try to generate a Validation that also includes the suffix,
        | the package will recognize this duplication and rename the Validation to remove the suffix.
        | This is the default behavior. To override and allow the duplication, change to false.
        |
        */
        'override_duplicate_suffix' => true,
    ],
];

使用

表单请求

要生成FormRequest类,请运行以下命令

php artisan adr:request CreateComment

使用默认后缀选项“Request”和默认命名空间选项“Http\Requests”,此命令将生成“App\Http\Requests\CreateCommentRequest”类。

注意:如果您在配置中设置了后缀,例如:“Request”,并运行以下命令

php artisan adr:request CreateCommentRequest

后缀将不会重复。要关闭此后缀重复检测,将“override_duplicate_suffix”选项更改为false。

下面是一个自定义表单请求类的示例

<?php

namespace App\Http\Requests;

use PerfectOblivion\Valid\BaseRequest;

class CustomClass extends BaseRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => ['required'],
        ];
    }

    /**
     * Get the sanitization filters that apply to the request.
     *
     * @return array
     */
    public function filters()
    {
        return [
            'name' => 'uppercase',
        ];
    }
}

注意:对于任何必要的预验证逻辑,您可以使用beforeValidation()方法。还有一个transform()方法可以在验证之前操纵数据。有关更多详细信息,请参阅PerfectOblivion\Valid\BaseRequest。

自定义规则

要生成自定义规则,请运行以下命令

php artisan adr:rule CustomRule

使用默认后缀选项“Rule”和默认命名空间选项“Rules”,此命令将生成“App\Rules\CustomRule”类。

注意:如果您在配置中设置了后缀,例如:“Rule”,并运行以下命令

php artisan adr:rule CustomRule

后缀将不会重复。要关闭此后缀重复检测,将“override_duplicate_suffix”选项更改为false。

有时,您可能需要在自定义规则类中访问当前表单请求和/或当前验证器中的信息。所有自定义规则都附带当前表单请求对象和当前验证器对象。您可以在自定义规则类中通过它们的属性来引用这些对象。请参见以下内容

<?php

namespace App\Rules;

use PerfectOblivion\Valid\CustomRule;

class NotSpamRule extends CustomRule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // if needed, access the current Validator with $this->validator and the current FormRequest with $this->request

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}

验证服务

如果您正在使用表单请求,则不需要同时使用验证服务。表单请求旨在由控制器使用,直接从当前请求中检索要验证的数据。验证服务用于验证域中其他类中的数据。

要生成验证服务,请运行以下命令

php artisan adr:validation StoreCommentValidation

使用默认后缀选项“Validation”和默认命名空间选项“Services”,此命令将生成“App\Services\StoreCommentValidation”类。

注意:如果您在配置中设置了后缀,例如:“Validation”,并运行以下命令

php artisan adr:validation StoreCommentValidation

后缀将不会重复。要关闭此后缀重复检测,将“override_duplicate_suffix”选项更改为false。

目前,验证服务必须从容器中解析。然后您调用validate()方法,传入要验证的数据数组。使用Laravel中任何自动从容器解析类的类,您可以使用验证服务,如下所示。这里我使用的是来自PerfectOblivion\Services的Service类,但是它可以在Laravel的任何自动解析类的组件中使用,如事件、作业等。

<?php

namespace App\Services;

use App\Comment;
use PerfectOblivion\Services\Traits\SelfCallingService;

class StoreCommentService
{
    use SelfCallingService;

    protected $params;

    /**
     * Construct a new StoreCommentService.
     */
    public function __construct(StoreCommentValidator $validator) // here, the validation service class is resolved from the container
    {
        $this->validator = $validator;
    }

    /**
     * Handle the call to the service.
     *
     * @return mixed
     */
    public function run($params)
    {
        $validated = $validator->validate($params); // we call the validate method, passing the array of parameters

        return Comment::create([
            'content' => $validated['content'], // the validated method returns the key/value pairs of data that was validaated
            'user_id' => auth()->user()->id,
        ]);
    }
}

与Laravel的表单请求一样,如果数据未通过验证,您将被重定向回表单,并显示错误。验证异常逻辑和重定向逻辑可以从ValidationService类内部自定义,就像在表单请求中一样。

以下是一个示例验证服务类

<?php

namespace App\Services;

use PerfectOblivion\Services\Validation\ValidationService;

class StoreCommentValidator extends ValidationService
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => ['required', new NotSpamRule()],
        ];
    }

    /**
     * Get the filters to apply to the data.
     *
     * @return array
     */
    public function filters()
    {
        return [
            'name' => 'uppercase',
        ];
    }
}

您可以在验证服务中使用我们的自定义规则和 waavi/sanitizer 过滤器,就像在自定义表单请求中一样。同样,与表单请求中的 CustomRules 一样,它给您提供了访问 $request 和 $validator 属性的权限,而在验证服务中使用的 CustomRules 则有 $validator 和 $service 属性,这些属性可以访问当前的 Validator 和当前的验证服务。

测试

composer test

变更日志

请参阅变更日志获取最近更改的更多信息。

贡献

请参阅贡献指南获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件 clay@phpstage.com 联系,而不是使用问题跟踪器。

路线图

我们计划很快着手进行灵活性和配置工作,以及发布一个框架无关的包版本。

鸣谢

许可

MIT 许可证(MIT)。请参阅许可文件获取更多信息。