徐767142206/x-validated

为 Hyperf 验证请求数据

v2.0.0-rc 2022-10-21 11:01 UTC

This package is auto-updated.

Last update: 2024-09-21 14:57:17 UTC


README

简易版注解验证库 for Hyperf, 基于 hyperf/validation

原因:一直很羡慕 springboot 的 validation 库,PHP 8 也已经有了原生的注解,就想到了套娃的方式简易实现,以后如果有空再想办法自己实现吧

安装

composer require xu767142206/x-validated

配置

1. config/autoload/exceptions.php 也可以自己实现 ValidationException 的处理

return [
    'handler' => [
        'http' => [
            //....
            Hyperf\Validation\ValidationExceptionHandler::class,
            //....
        ],
    ],
];

使用

DTO 模型的定义

DTO 模型必须继承 XValidated\ValidatedData

模型定义

use XValidated\Annotation\Rule;
use XValidated\ValidatedData;

class LoginDto extends ValidatedData
{
    #[Rule(values: ["required"])]
    public int $phone;

    #[Rule(values: ["required"], alias: "pass_word", messages: ['required' => "密码不能为空"])]
    public string $password;
}

rule 规则可以查看 hyperf/validation 库的验证规则 验证规则

然后创建控制器 IndexController

use XValidated\Annotation\Validated;
use App\Model\LoginDto;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

#[AutoController]
class IndexController extends AbstractController
{
    #[RequestMapping(path: "index", methods: "get,post")]
    #[Validated]
    public function index(RequestInterface $request, LoginDto $loginDto)
    {
        var_dump($loginDto->toArray());
        return [
            'param' => $request->getServerParams(),
        ];
    }
}

接着可以快乐的写代码了

许可协议

MIT