Symfony Integration
Complete guide for using Data Helpers with Symfony.
Introduction
Section titled “Introduction”Data Helpers provides seamless Symfony integration:
- ✅ Automatic Bundle - Zero configuration with Flex
- ✅ Value Resolver - Automatic controller injection
- ✅ Doctrine Integration - fromEntity(), toEntity()
- ✅ Security Integration - WhenGranted, WhenSymfonyRole
- ✅ Validator Integration - Automatic validation
- ✅ Console Commands - make:dto, dto:typescript
- ✅ Serializer Integration - Normalizers
Installation
Section titled “Installation”composer require event4u/data-helpersWith Symfony Flex
Section titled “With Symfony Flex”Symfony Flex automatically registers the bundle. No configuration needed!
Without Flex
Section titled “Without Flex”Add to config/bundles.php:
return [ // ... event4u\DataHelpers\Frameworks\Symfony\DataHelpersBundle::class => ['all' => true],];Configuration (Optional)
Section titled “Configuration (Optional)”Create config/packages/data_helpers.yaml:
data_helpers: validation: enabled: true cache: trueController Integration
Section titled “Controller Integration”Automatic Injection
Section titled “Automatic Injection”Type-hint your DTO in controller methods:
use App\DTO\UserRegistrationDTO;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\Routing\Annotation\Route;
class UserController extends AbstractController{ #[Route('/register', methods: ['POST'])] public function register(UserRegistrationDTO $dto): JsonResponse { // $dto is automatically validated and filled with request data $user = new User(); $dto->toEntity($user);
$this->entityManager->persist($user); $this->entityManager->flush();
return $this->json($user, 201); }}How It Works
Section titled “How It Works”- Symfony’s ValueResolver detects the DTO type hint
- Request data is extracted (JSON or form data)
- DTO is created and validated
- Controller receives the validated DTO
Manual Creation
Section titled “Manual Creation”#[Route('/register', methods: ['POST'])]public function register(Request $request): JsonResponse{ $dto = UserRegistrationDTO::fromRequest($request); $dto->validate(); // Throws ValidationException on failure
$user = new User(); $dto->toEntity($user);
return $this->json($user, 201);}Doctrine Integration
Section titled “Doctrine Integration”From Doctrine Entity
Section titled “From Doctrine Entity”$user = $this->entityManager->find(User::class, 1);$dto = UserDTO::fromEntity($user);To Doctrine Entity
Section titled “To Doctrine Entity”$dto = UserDTO::fromArray($data);$user = new User();$dto->toEntity($user);
$this->entityManager->persist($user);$this->entityManager->flush();Update Existing Entity
Section titled “Update Existing Entity”$user = $this->entityManager->find(User::class, 1);$dto = UserDTO::fromRequest($request);$dto->toEntity($user);
$this->entityManager->flush();Symfony Security Integration
Section titled “Symfony Security Integration”WhenGranted
Section titled “WhenGranted”Show property when user has permission:
use event4u\DataHelpers\SimpleDTO\Attributes\WhenGranted;
class UserProfileDTO extends SimpleDTO{ public function __construct( public readonly string $name,
#[WhenGranted('ROLE_ADMIN')] public readonly ?string $email = null, ) {}}WhenSymfonyRole
Section titled “WhenSymfonyRole”Show property when user has role:
use event4u\DataHelpers\SimpleDTO\Attributes\WhenSymfonyRole;
#[WhenSymfonyRole('ROLE_ADMIN')]public readonly ?array $adminPanel = null;
// Multiple roles (OR logic)#[WhenSymfonyRole(['ROLE_ADMIN', 'ROLE_MODERATOR'])]public readonly ?array $moderationPanel = null;Validation Integration
Section titled “Validation Integration”Symfony Validator Attributes
Section titled “Symfony Validator Attributes”use Symfony\Component\Validator\Constraints as Assert;
class UserDTO extends SimpleDTO{ public function __construct( #[Assert\NotBlank] #[Assert\Email] public readonly string $email,
#[Assert\NotBlank] #[Assert\Length(min: 8)] public readonly string $password, ) {}}SimpleDTO Validation Attributes
Section titled “SimpleDTO Validation Attributes”use event4u\DataHelpers\SimpleDTO\Attributes\*;
class UserDTO extends SimpleDTO{ public function __construct( #[Required, Email] public readonly string $email,
#[Required, Min(8)] public readonly string $password, ) {}}Console Commands
Section titled “Console Commands”Generate DTO
Section titled “Generate DTO”php bin/console make:dto UserDTOCreates src/DTO/UserDTO.php:
<?php
namespace App\DTO;
use event4u\DataHelpers\SimpleDTO\SimpleDTO;
class UserDTO extends SimpleDTO{ public function __construct( public readonly string $name, public readonly string $email, ) {}}Generate TypeScript
Section titled “Generate TypeScript”php bin/console dto:typescriptGenerates TypeScript interfaces from your DTOs.
See also: Console Commands - Complete guide to all available console commands
Real-World Example
Section titled “Real-World Example”use App\DTO\CreateUserDTO;use App\Entity\User;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\Routing\Annotation\Route;
class UserController extends AbstractController{ public function __construct( private EntityManagerInterface $em, ) {}
#[Route('/users', methods: ['POST'])] public function create(CreateUserDTO $dto): JsonResponse { $user = new User(); $dto->toEntity($user);
$this->em->persist($user); $this->em->flush();
return $this->json($user, 201); }
#[Route('/users/{id}', methods: ['GET'])] public function show(int $id): JsonResponse { $user = $this->em->find(User::class, $id); $dto = UserDTO::fromEntity($user);
return $this->json($dto); }
#[Route('/users/{id}', methods: ['PUT'])] public function update(int $id, UpdateUserDTO $dto): JsonResponse { $user = $this->em->find(User::class, $id); $dto->toEntity($user);
$this->em->flush();
return $this->json($user); }}Code Examples
Section titled “Code Examples”The following working examples demonstrate Symfony integration:
- Symfony Doctrine - Symfony with Doctrine
All examples are fully tested and can be run directly.
Related Tests
Section titled “Related Tests”The functionality is thoroughly tested. Key test files:
- SymfonyIntegrationTest.php - Symfony integration tests
Run the tests:
# Run Symfony teststask test:unit -- --filter=Symfony
# Run E2E testscd tests-e2e/Symfony && composer install && vendor/bin/phpunitSee Also
Section titled “See Also”- Doctrine Integration - Doctrine entity mapping
- Validation Attributes - Validation reference
- Conditional Attributes - Conditional visibility