20、Hyperf 3 快速使用 - 表单数据验证
hi,我是温新,一名 PHPer
Hypref 版本:Hyperf 3.0
学习目标:掌握表单数据验证
准备工作
注意,目前 Hyperf 3.0 中, 安装验证包会报错,解决方法是 删除 composer.lock 后,再进行安装
第一步:安装组件包
composer require hyperf/validation
第二步:发布验证器语言文件
# translation 若存在可以不发布
php bin/hyperf.php vendor:publish hyperf/translation
php bin/hyperf.php vendor:publish hyperf/validation
该命令会在 /storage/languages
目录生成 en
和 zh_CN
目录并在这两个目录下生成对应的语言文件。
第三步:添加中间件
<?php
// config/autoload/middlewares.php
declare(strict_types=1);
return [
'http' => [
\Hyperf\Validation\Middleware\ValidationMiddleware::class
],
];
第四步:添加异常处理器
异常处理器主要对 Hyperf\Validation\ValidationException
异常进行处理,Hyperf 提供了一个 Hyperf\Validation\ValidationExceptionHandler
来进行处理。需要手动将这个异常处理器配置到您的项目的 config/autoload/exceptions.php
文件内。
<?php
// config/autoload/exceptions.php
declare(strict_types=1);
return [
'handler' => [
'http' => [
Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
\Hyperf\Validation\ValidationExceptionHandler::class,
],
],
];
第五步:创建控制器
<?php
namespace App\Controller\Test;
use App\Request\UserRequest;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\View\RenderInterface;
#[Controller]
class UserController
{
#[GetMapping('/users/create')]
public function create(RenderInterface $render)
{
return $render->render('users.create');
}
}
第六步:创建视图
<!-- /storage/view/users/create.blade.php -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户注册</title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<form action="/users/store" method="post">
<div class="mb-3">
<label for="name" class="form-label">用户名</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="mb-3">
<label for="email" class="form-label">邮箱</label>
<input type="text" class="form-control" id="email" name="email">
</div>
<div class="mb-3">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="mb-3">
<label for="password_confirmation " class="form-label">确认密码</label>
<input type="password" class="form-control" id="password_confirmation" name="password_confirmation">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary mb-3">注册用户</button>
</div>
</form>
</body>
</html>
使用验证器
方式一:表单请求验证
第一步:创建表单请求类
对于复杂的验证可以,可以使用表单请求来验证。表单请求是包含验证逻辑的一个自定义请求类。
# 创建表单请求验证处理类
php bin/hyperf.php gen:request UserRequest
该命令会在 app\Request
目录下生成 UserRequest.php
文件。
第二步:编写表单请求类
<?php
declare(strict_types=1);
namespace App\Request;
use Hyperf\Validation\Request\FormRequest;
class UserRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
// 表单验证规则
public function rules(): array
{
return [
'name' => 'required',
'password' => 'required|confirmed',
'email' => 'required|email',
];
}
public function messages(): array
{
return [
'name.required' => '用户名必须填写'
];
}
}
表单验证失败时,验证器会抛出一个 Hyperf\Validation\ValidationException
异常,我们可以使用自定义异常处理类来处理该异常。
第三步:控制器使用
// App\Controller\Test\UserController.php
// UserRequest 验证,表单提交后会自动验证
#[PostMapping('/users/store')]
public function store(UserRequest $request)
{
// 验证通过后的数据
$data = $request->validated();
}
方式二:手动创建验证器
<?php
// App\Controller\Test\UserController.php
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
#[Inject]
protected ValidatorFactoryInterface $validatorFactory;
#[PostMapping('/users/store')]
public function store(RequestInterface $request)
{
$validator = $this->validatorFactory->make($request->all(), [
'name' => 'required',
'password' => 'required|confirmed',
'email' => 'required|email',
],[
'name.required' => '用户名必须填写'
]);
if ($validator->fails()) {
// 进行异常处理
// 获取错误信息
$validator->errors()->first();
}
}
验证包安装报错个坑,大家一定要注意。
请登录后再评论