kooditorm / hyperf-validation
Annotation validator for the Hyperf framework
dev-master
2026-03-25 09:58 UTC
Requires
- php: >=8.1
- hyperf/exception-handler: ^3.1.0
- hyperf/http-message: ^3.1.0
- hyperf/http-server: ^3.1.0
- hyperf/validation: ^3.1.0
This package is auto-updated.
Last update: 2026-03-25 09:58:43 UTC
README
基于注解的 Hyperf 框架验证器扩展包,通过属性注解实现优雅的数据验证。
安装
composer require kooditorm/hyperf-validation
特性
- 🚀 基于 PHP8.1+ 属性注解
- 💎 优雅的 AOP 切面验证
- 📦 支持自定义验证规则
- 🎯 自动类型转换
- 🌐 支持自定义错误消息
✅ 数据验证
内置验证注解
需要先安装 Hyperf 验证器:
composer require hyperf/validation
本库提供了丰富的验证注解,包括:
| 框架规则 | 使用规则 |
|---|---|
required |
NotBlank |
regex |
Pattern |
array |
IsArray |
支持验证規則:
accepted、accepted_if
declined、declined_if
active_url
after、after_or_equal
before、before_or_equal
alpha、alpha_dash、alpha_num
ascii
array、required_array_keys
between
confirmed
data、date_equals、date_format
decimal
lowercase、uppercase、mac_address
digits、digits_between、max_digits、min_digits
email
file、image
in、in_array
gt、 gte、lt、lte
特殊用法说明 IsArray(value:1,2,3)
框架用法: 'name' => "array:1,2,3"
验证结果: 当验证规则存在参数,验证数组的键必须存在一个或多个参数包含的值,且不能出现不存在的键
| 验证的数组 | 结果 |
|---|---|
| "name": {"1": 1, "4": 2} | false |
| "name": {"1": 1, "2": 2} | true |
| "name": {"1": 1, "2": 2, "3":3} | true |
| "name": {"1": 1, "2": 2, "4":3} | false |
| "name": {"1": 1, "2": 2, "3":3, "4":4} | false |
RequiredArrayKeys(value:1,2,3)
框架用法: 'name' => "required_array_keys:a,b,c"
原文檔描述:验证的字段必须是一个数组,并且必须至少包含指定的键。
验证结果: 验证的字段必须是一个数组,并且必须包含所有的键。
| 验证的数组 | 结果 |
|---|---|
| "name": {"a": "1","b": "b"} | false |
| "name": {"a": "1","b": "b","c":"c"} | true |
| "name": {"a": "1","b": "b","d":"c"} | false |
| "name": {"a": "1","b": "b","c":"c","d":"d"} | false |
备注:
- 具体规则请查看 Hyperf 验证器文档。
- 除上述表格外,其他均为常规调用方法。 常规调用为规则名称的大驼峰,如
Accepted、AcceptedIf。
快速开始
1. 基础用法
在控制器方法上使用 #[Validated] 注解:
<?php declare(strict_types=1); namespace App\Controller; use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\PostMapping; use Kooditorm\Validation\Annotation\Validated; #[Controller(prefix: "user")] class UserController { #[PostMapping(path: "create")] #[Validated(instance: CreateUserRequest::class)] public function create() { // 验证通过后的业务逻辑 return ['message' => '创建成功']; } }
2. 定义验证规则类
创建验证请求类,使用属性注解定义验证规则:
<?php declare(strict_types=1); namespace App\Request; use Kooditorm\Validation\Annotation\Rules\NotBlank; use Kooditorm\Validation\Annotation\Rules\Pattern; class CreateUserRequest { #[NotBlank(message: '用户名不能为空')] private string $username; #[NotBlank(message: '邮箱不能为空')] #[Pattern(value: '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', message: '邮箱格式不正确')] private string $email; #[NotBlank(message: '密码不能为空')] private string $password; // Getters and Setters public function getUsername(): string { return $this->username; } public function setUsername(string $username): self { $this->username = $username; return $this; } public function getEmail(): string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } public function getPassword(): string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } }
3. 直接使用 Valid 注解
也可以直接在方法参数上使用 #[Valid] 注解:
#[PostMapping(path: "update")] #[Valid] public function update(UpdateUserRequest $request) { return ['message' => '更新成功']; }
内置验证规则
类型验证
支持 PHP 原生类型声明,会自动转换为对应的验证规则:
class UserRequest { // 转换为 'integer' 规则 private int $age; // 转换为 'string' 规则 private string $name; // 转换为 'boolean' 规则 private bool $status; // 转换为 'array' 规则 private array $tags; }
支持的类型转换:
int→integer- 其他 PHP 类型保持原名
可用注解规则
NotBlank
必填项验证:
use Kooditorm\Validation\Annotation\Rules\NotBlank; #[NotBlank(message: '此项为必填项')] private string $field;
参数说明:
message: 错误消息rule: 验证规则(默认required)filed: 字段名(可选)
Pattern
正则表达式验证:
use Kooditorm\Validation\Annotation\Rules\Pattern; #[Pattern( value: '/^\d{11}$/', message: '手机号格式不正确' )] private string $phone;
参数说明:
value: 正则表达式模式message: 错误消息rule: 验证规则(默认regex:{$value})field: 字段名(可选)
自定义验证规则
继承 ValidatorAnnotation 抽象类创建自定义规则:
<?php declare(strict_types=1); namespace App\Validation\Rules; use Attribute; use Kooditorm\Validation\Annotation\ValidatorAnnotation; #[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] class MaxLength extends ValidatorAnnotation { public function __construct( public int $length, public string $message = '', public string $rule = 'max:{$length}', ) { } }
使用自定义规则:
class PostRequest { #[MaxLength(length: 100, message: '标题长度不能超过 100 个字符')] private string $title; }
高级用法
可空字段
使用 PHP 的类型系统声明可空字段:
class UserRequest { // 会自动添加 'nullable' 规则 private ?string $nickname = null; private ?int $age = null; }
多个验证规则
同一个字段可以应用多个验证规则注解:
class RegisterRequest { #[NotBlank(message: '用户名不能为空')] #[Pattern(value: '/^[a-zA-Z][a-zA-Z0-9_]{4,19}$/', message: '用户名格式不正确')] private string $username; #[NotBlank(message: '密码不能为空')] #[Pattern(value: '/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/', message: '密码必须包含字母和数字,且长度不少于 6 位')] private string $password; }
异常处理
验证失败会抛出 ValidationException 异常,默认状态码为 422。
自定义异常处理器
包内已提供默认的异常处理器 ValidateExceptionHandler,如需自定义:
<?php declare(strict_types=1); namespace App\Exception\Handler; use Hyperf\HttpMessage\Stream\SwooleStream; use Kooditorm\Validation\Exception\ValidationException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; class CustomValidateExceptionHandler extends \Hyperf\ExceptionHandler\AbstractExceptionHandler { protected array $ignore = [ ValidationException::class, ]; public function handle(Throwable $throwable, ServerRequestInterface $request): ResponseInterface { if ($throwable instanceof ValidationException) { return $this->response->json([ 'code' => 422, 'message' => $throwable->getMessage(), 'data' => null, ])->withStatus(422); } return $this->response->json([ 'code' => 500, 'message' => '服务器内部错误', ])->withStatus(500); } public function isValid(Throwable $throwable): bool { return true; } }
工作原理
本包利用 Hyperf 的 AOP 切面编程和注解功能:
ValidatorAspect切面拦截标注了#[Validated]或#[Valid]的方法- 从方法参数或注解中获取验证规则类
- 通过反射读取属性的类型声明和验证注解
- 构建验证规则和消息数组
- 使用 Hyperf 原生的验证器进行验证
- 验证失败抛出
ValidationException异常
注意事项
- PHP 版本要求: 需要 PHP 8.1 或更高版本
- Hyperf 版本: 需要 Hyperf 3.1.0 或更高版本
- 属性扫描: 确保配置文件中扫描了相关路径
- 类型声明: 建议使用严格的类型声明以获得更好的验证效果
许可证
MIT License
贡献
欢迎提交 Issue 和 Pull Request!
作者
- oswin.hu oswin.hu@gmail.com