vi-tech / dto-bundle
DTO resolver for symfony projects
Installs: 9 345
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 4
Forks: 0
Open Issues: 2
Requires
- php: ^7.3|~8.0.0|^8.1
- ext-json: *
- spatie/data-transfer-object: ^1.13|^2.5
- symfony/dependency-injection: ^4.1|^5.0|^6.0
- symfony/http-kernel: ^4.1|^5.1|^6.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.2
- phpunit/phpunit: ^9.3
- roave/security-advisories: dev-master
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-10-29 06:00:09 UTC
README
Package for an automatic request to predefined structures conversion in symfony applications.
Installation
$ composer require vi-tech/dto-bundle
Declare bundle in configuration:
// config/bundles.php return [ \ViTech\DataObjectBundle\DataObjectBundle::class => ['all' => true], ];
Usage
<?php use Symfony\Component\HttpFoundation\Response; use ViTech\DataObjectBundle\Object\AbstractObject; class RegistrationDto extends AbstractObject { /** @var string */ public $login; /** @var string */ public $password; } class RegistrationController { public function __invoke(RegistrationDto $registration): Response { // Register new user using $registration // $registration->login contains Request::$request->get('login'). Same for password. return new Response(); } }
Data in RegistrationDto $registration
matches Request::$request properties.
If request contains properties that are not declared in DTO they will be omitted.
On property type mismatch Symfony\Component\HttpKernel\Exception\BadRequestHttpException
will be thrown.
It is a common approach to validate DTO within application.
The simplest way to do that is to declare constraints annotations for the same DTO and use symfony validator.
<?php use Symfony\Component\HttpFoundation\Response; use ViTech\DataObjectBundle\Object\AbstractObject; use Symfony\Component\Validator\Validator\ValidatorInterface; class RegistrationDto extends AbstractObject { /** * @Assert\NotBlank() * @Assert\UniqueLogin() * * @var string */ public $login; /** * @Assert\NotBlank() * @Assert\PasswordRules() * * @var string */ public $password; } class RegistrationController { /** @var ValidatorInterface */ private $validator; public function __invoke(RegistrationDto $registration): Response { $violations = $this->validator->validate($registration); if (count($violations)) { // Handle constraints violations } // register new user using $registration return new Response(); } }