1. Go to this page and download the library: Download macpaw/request-dto-resolver library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// src/DTO/UserDto.php
namespace App\DTO;
use Symfony\Component\Validator\Constraints as Assert;
class UserDto implements RequestDtoInterface
{
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
public string $name;
#[Assert\NotBlank]
#[Assert\Email]
public string $email;
/** @var string[] */
#[Assert\Count(min: 1)]
#[Assert\All([
new Assert\NotBlank,
new Assert\Length(min: 2)
])]
public array $tags = [];
}
// src/Form/UserFormType.php
namespace App\Form;
use App\DTO\UserDto;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class)
->add('email', EmailType::class)
->add('tags', CollectionType::class, [
'entry_type' => TextType::class,
'allow_add' => true,
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => UserDto::class,
]);
}
}
// src/Controller/UserController.php
namespace App\Controller;
use App\DTO\UserDto;
use App\Form\UserFormType;
use RequestDtoResolver\Attribute\FormType;
use Symfony\Component\HttpFoundation\JsonResponse;
class UserController
{
#[FormType(UserFormType::class)]
public function __invoke(UserDto $dto): JsonResponse
{
// $dto is now a validated and populated object
return new JsonResponse([
'name' => $dto->name,
'email' => $dto->email,
'tags' => $dto->tags,
]);
}
}