zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

带你学习hyperf-3.7 验证器

2023-04-18 16:22:07 时间

3.7 验证器

与laravel的表单验证基本相同

1. 安装composer类库

composer require hyperf/validation

Bash

Copy

2. 设置表单验证的中间件:config/autoload/middlewares.php

<?php

return [
    'http' => [
        HyperfValidationMiddlewareValidationMiddleware::class
    ],
];

PHP

Copy

3. 添加表单验证出错的异常处理

<?php

return [
    'handler' => [
        'http' => [
            // 验证器的异常处理
            HyperfValidationValidationExceptionHandler::class,

            HyperfHttpServerExceptionHandlerHttpExceptionHandler::class,
            AppExceptionHandlerAppExceptionHandler::class,
        ],
    ],
];

PHP

Copy

4. 创建验证器语言文件

php bin/hyperf.php vendor:publish hyperf/translation
php bin/hyperf.php vendor:publish hyperf/validation

PHP

Copy

5. 使用:表单验证类

php bin/hyperf.php gen:request CreateUserRequest

Bash

Copy

  • 定义规则
<?php
/**
 * 表单的验证类
 */
namespace AppRequest;

use HyperfValidationRequestFormRequest;

class CreateUserRequest extends FormRequest
{
    /**
     * 是否验证完成后允许放行
     * @return bool
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * 验证规则
     * @return array|string[][]
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string'],
            'password' => ['required', 'min:6']
        ];
    }

    /**
     * 验证的各字段的含义
     * @return array|string[]
     */
    public function attributes(): array
    {
        return [
            'name' => '用户名',
            'password' => '密码'
        ];
    }
}

PHP

Copy

  • 依赖注入的方式验证
<?php
/**
 * 控制器
 */
namespace AppController;

use AppRequestCreateUserRequest;

class IndexController extends AbstractController
{
    public function index(CreateUserRequest $request)
    {
        // 返回验证通过的字段
        return $request->validated();
    }
}

PHP

Copy

  • 使用:通过表单验证对象
<?php
namespace AppController;

class IndexController extends AbstractController
{
    /**
     * @HyperfDiAnnotationInject()
     * @var HyperfValidationContractValidatorFactoryInterface
     */
    protected $validationFactory;

    public function index()
    {
        // 表演的验证规则
        $validator = $this->validationFactory->make(
            $this->request->all(),
            [
                'name' => ['required', 'string'],
                'password' => ['required', 'min:6'],
            ]
        );
        // 判断是否有出错
        if ($validator->fails()){
            // 错误信息
            return [
                'error' => $validator->errors()->first()
            ];
        }

        // 返回验证通过的字段
        return $validator->validated();
    }
}

PHP

Copy

注:自定义验证属性