Yii Validating Hydrator 1.0
2024-02-02
1129次浏览
First stable release of yiisoft/hydrator-validator was tagged.
The package provides a hydrator that also does validation, including raw data. It's useful when input data comes from a user, and you need to validate it and then put it into DTOs.
To use it, the object being validated must implement ValidatedInputInterface
. You can use ValidatedInputTrait
to easily create such object. The validation rules for raw values of the object are defined with Validate
PHP attribute.
Example of object:
use Yiisoft\Hydrator\Validator\Attribute\Validate;
use Yiisoft\Hydrator\Validator\ValidatedInputInterface;
use Yiisoft\Hydrator\Validator\ValidatedInputTrait;
use Yiisoft\Validator\Rule\Email;
use Yiisoft\Validator\Rule\Required;
final class InputDto implements ValidatedInputInterface
{
use ValidatedInputTrait;
#[Email]
private string $email;
#[Validate(new Required())]
private string $name;
}
Validation result could be obtained via its getValidationResult()
method.
Validating hydrator usage example:
use Yiisoft\Hydrator\HydratorInterface;
use Yiisoft\Hydrator\Validator\ValidatingHydrator;
public function actionEdit(RequestInterface $request, ValidatingHydrator $hydrator): ResponseInterface
{
$data = $request->getParsedBody();
$inputDto = $hydrator->create(InputDto::class, $data);
if (!$inputDto->getValidationResult()->isValid()) {
// Validation didn't pass :(
}
// Everything is fine. You can use $inputDto now.
}
新闻归档
热门标签
- yii3
- 扩展
- 发布
- yii2
- debug
- view
- auth client
- html
- bootstrap
- release
- apidoc
- Yii 1.1
- redis
- Yii 2.0
- mongodb
- extensions
- mailer
- runner
- gii
- console
- http 客户端
- queue
- validation
- twig
- error handler
- hydrator
- http
- translator
- cache
- widget
- sphinx
- config
- symfonymailer
- assets
- db
- log
- router
- swagger
- swiftmailer
- elasticsearch
- 图书
- imagine
- fastroute
- rbac
- i18n
- IDE
- user
- definitions
- csrf
- widgets