hesb / hyperf-dto-validation
php hyperf dto validation
1.0.0
2024-11-27 08:11 UTC
Requires
- php: >=8.2
- hesb/hyperf-dto: *
- hyperf/di: ~3.0.0
- hyperf/http-server: ~3.0.0
- hyperf/validation: ~3.0.0
- netresearch/jsonmapper: ~4.0.0
- phpdocumentor/reflection-docblock: ^5.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- mockery/mockery: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: >=7.0
- symfony/var-dumper: ^5.1
This package is not auto-updated.
Last update: 2025-04-03 07:21:43 UTC
README
介绍
基于 tw2066/dto 框架改进而来,特别鸣谢tw2066/dto给的灵感
运行环境
- php >= 8.2
- hyperf >= 3.0
安装
composer require hesb/hyperf-dto-validation
使用
创建简单dto
<?php
declare(strict_types=1);
namespace Hesb\Hyperf\Example\DTO;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\Between;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\Email;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\In;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\Integer;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\Nullable;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\Required;
use Hesb\Hyperf\DTO\Validation\Annotation\Rule\Validation;
class Address
{
#[Required(messages: '请输入对应的文本')]
#[Between(1,5)]
#[Email]
#[In(1,5)]
#[Integer]
#[Nullable]
#[Required]
public string $street;
public float $float;
public int $int;
/** @var array<int,string> */
public array $array;
public LoginTokenTypeEnum $loginTokenTypeEnum;
public ?City $city = null;
}
---
class City
{
public string $name;
}
---
enum LoginTokenTypeEnum: string
{
case jwt = 'jwt';
case password = 'password';
}
引用
注意: 一个方法,不能同时注入RequestBody和RequestFormData
use Hesb\Hyperf\DTO\Annotation\Contracts\RequestBody;
use Hesb\Hyperf\DTO\Annotation\Contracts\RequestQuery;
use Hesb\Hyperf\DTO\Annotation\Contracts\RequestFormData;
use Hesb\Hyperf\DTO\Validation\Annotation\Contracts\Valid;
public function add(#[RequestBody] #[Valid] Address $request){}
public function add(#[RequestQuery] #[Valid] Address $request){}
public function fromData(#[RequestFormData] #[Valid] Address $formData){}
public function add(#[RequestBody] #[Valid] DemoBodyRequest $request, #[RequestQuery] #[Valid] DemoQuery $query){}
例子
class DemoController extends AbstractController
{
public function index(#[RequestQuery] #[Valid] DemoQuery $request): Contact
{
$contact = new Contact();
$contact->name = $request->name;
var_dump($request);
return $contact;
}
public function add(#[RequestBody] #[Valid] DemoBodyRequest $request, #[RequestQuery] DemoQuery $query)
{
var_dump($query);
return json_encode($request, JSON_UNESCAPED_UNICODE);
}
public function fromData(#[RequestFormData] #[Valid] DemoFormData $formData): bool
{
$file = $this->request->file('photo');
var_dump($file);
var_dump($formData);
return true;
}
}