VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/7-validated-dtos-and-type-casting

⇱ Validated DTOs and Type Casting | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Validated DTOs and Type Casting

The Validated DTO component provides type-safe Data Transfer Objects with automatic validation and casting for Hyperf applications. DTOs can be instantiated from multiple sources (HTTP requests, arrays, JSON, Eloquent models, console commands), validated using Hyperf's validation system, and automatically cast to appropriate PHP types. The component offers two base classes: SimpleDTO for basic data transfer without validation, and ValidatedDTO for validated data with rules defined via attributes or methods.

This component is located at src/validated-dto/ and registered via FriendsOfHyperf\ValidatedDTO\ConfigProvider.

For HTTP request handling patterns, see page 3.3. For database model integration, see page 6.

Component Architecture

The DTO system is built around two abstract base classes that provide different levels of functionality:

Component Structure


Sources: src/validated-dto/src/SimpleDTO.php1-577 src/validated-dto/src/ValidatedDTO.php1-224 src/validated-dto/src/Casting/ src/validated-dto/src/Attributes/

SimpleDTO vs ValidatedDTO

The component provides two base classes with different capabilities:

FeatureSimpleDTOValidatedDTO
Type casting
Property mapping
Multiple data sources
Export to array/JSON/Model
Validation rules
Automatic validation
Validation scenes
Custom validation messages
Lazy validation

SimpleDTO at src/validated-dto/src/SimpleDTO.php implements the core DTO functionality including instantiation from various sources (DataResolver trait), type casting via the Castable system, property mapping, and export methods (DataTransformer trait).

ValidatedDTO at src/validated-dto/src/ValidatedDTO.php extends SimpleDTO and integrates with Hyperf's ValidatorFactoryInterface. Validation occurs automatically during construction via the isValidData() method at src/validated-dto/src/ValidatedDTO.php148-174 unless $lazyValidation is enabled.

Sources: src/validated-dto/src/SimpleDTO.php44-104 src/validated-dto/src/ValidatedDTO.php25-224

Basic Usage

Creating DTO Instances

DTOs can be instantiated from multiple sources via static factory methods in the DataResolver trait:

Data Source Methods


Example Usage:


Sources: src/validated-dto/src/Concerns/DataResolver.php src/validated-dto/src/SimpleDTO.php84-99 tests/ValidatedDTO/Unit/ValidatedDTOTest.php95-202

Defining a DTO Class

A typical DTO class extends ValidatedDTO or SimpleDTO and defines properties with optional attributes:


The DTO can then be instantiated and used:


Sources: src/validated-dto/src/Command/stubs/dto.stub tests/ValidatedDTO/Datasets/

Key Features

Validation Integration

ValidatedDTO automatically validates data during instantiation using Hyperf's ValidatorFactoryInterface. Validation rules are defined via the rules() method or #[Rules] attributes:


The validation flow at src/validated-dto/src/ValidatedDTO.php148-174 creates a validator, applies rules, and throws ValidationException if validation fails. For details on validation rules, scenes, and lazy validation, see page 5.1.

Sources: src/validated-dto/src/ValidatedDTO.php148-174 src/validated-dto/src/SimpleDTO.php373-378

Type Casting

Properties are automatically cast to their declared types using the casting system. Casts are defined via the casts() method or #[Cast] attributes:


The casting system at src/validated-dto/src/SimpleDTO.php296-311 supports 12 built-in cast types including ArrayCast, BooleanCast, CarbonCast, CollectionCast, DTOCast, EnumCast, IntegerCast, and more. Custom casters can be created by implementing the Castable interface. For detailed information on casting, see page 5.2.

Sources: src/validated-dto/src/SimpleDTO.php296-311 src/validated-dto/src/Casting/

Property Mapping

The mapping system transforms property names between external data and DTO properties. Input mapping via mapData() occurs before validation, while output mapping via mapToTransform() occurs during export:


The mapping system at src/validated-dto/src/SimpleDTO.php443-490 supports dot notation for nested structures. For complete documentation on property mapping, see page 5.3.

Sources: src/validated-dto/src/SimpleDTO.php443-490 src/validated-dto/src/Attributes/Map.php

Default Values

Default values are applied when properties are missing or null. Defaults can be defined via the defaults() method or #[DefaultValue] attribute:


Defaults are processed at src/validated-dto/src/SimpleDTO.php206-233 after validation but before casting. For more information, see page 5.3.

Sources: src/validated-dto/src/SimpleDTO.php206-233 src/validated-dto/src/Attributes/DefaultValue.php

Export and Serialization

DTOs can be exported to multiple formats via the DataTransformer trait:


The export process at src/validated-dto/src/SimpleDTO.php342-357 applies output mapping via mapToTransform(), then recursively transforms nested DTOs, Collections, and other complex types through formatArrayableValue() at src/validated-dto/src/SimpleDTO.php502-515 For detailed documentation on export formats, see page 5.4.

Sources: src/validated-dto/src/Concerns/DataTransformer.php src/validated-dto/src/SimpleDTO.php342-357 src/validated-dto/src/SimpleDTO.php502-515

Attributes and Metadata

PHP 8 attributes provide declarative configuration for DTO properties. Four attributes are available:

AttributePurposeExample
#[Rules]Validation rules#[Rules(['required', 'email'])]
#[Cast]Type casting#[Cast(CarbonCast::class)]
#[DefaultValue]Default value#[DefaultValue('active')]
#[Map]Property mapping#[Map(data: 'user_name')]

Attributes are processed via reflection in buildAttributesData() at src/validated-dto/src/SimpleDTO.php369-409 and stored in internal arrays ($dtoRules, $dtoCasts, $dtoDefaults, $dtoMapData, $dtoMapTransform). For detailed attribute usage, see page 5.3.

Example:


Sources: src/validated-dto/src/SimpleDTO.php369-409 src/validated-dto/src/Attributes/

Integration with Hyperf

The DTO system integrates with Hyperf's ecosystem through several mechanisms:

Model Casting

DTOs implement CastsAttributes from Hyperf and can be used as Eloquent model cast types:


The get() and set() methods at src/validated-dto/src/SimpleDTO.php122-155 handle the conversion between model attributes and DTO instances.

Validation System

ValidatedDTO uses Hyperf's ValidatorFactoryInterface at src/validated-dto/src/ValidatedDTO.php150-157 to create validators with the same rule syntax as Hyperf's validation component.

ConfigProvider Registration

The component registers via FriendsOfHyperf\ValidatedDTO\ConfigProvider as specified in src/validated-dto/composer.json47-49 enabling automatic discovery by Hyperf's DI container.

Command Generation

A console command is available to generate DTO class stubs:


The command uses the stub at src/validated-dto/src/Command/stubs/dto.stub to generate a DTO class with all configuration methods pre-defined.

Sources: src/validated-dto/src/SimpleDTO.php122-155 src/validated-dto/src/ValidatedDTO.php148-164 src/validated-dto/composer.json47-49 src/validated-dto/src/Command/

Error Handling

The DTO system throws specific exceptions for various error conditions:

ExceptionThrown WhenSource Location
ValidationExceptionValidation fails in ValidatedDTOsrc/validated-dto/src/ValidatedDTO.php171-174
InvalidJsonExceptionJSON parsing fails in fromJson()src/validated-dto/src/Concerns/DataResolver.php
MissingCastTypeExceptionProperty requires casting but no caster defined (when requireCasting is true)src/validated-dto/src/SimpleDTO.php217-219
CastTargetExceptionInvalid cast target or type mismatchsrc/validated-dto/src/SimpleDTO.php306-308
CastExceptionCast operation fails (thrown by individual Castable implementations)Various Castable classes

The requireCasting configuration option can be set globally via config/dto.php or per-DTO instance. When enabled, it enforces that all properties must have an explicit cast definition.

Sources: src/validated-dto/src/SimpleDTO.php536-547 src/validated-dto/src/ValidatedDTO.php171-174 src/validated-dto/src/SimpleDTO.php217-219

Integration with Hyperf Ecosystem

The DTO system integrates with several Hyperf components:

Model Casting

DTOs can be used as Eloquent model cast types by implementing CastsAttributes:


Sources: src/validated-dto/src/SimpleDTO.php122-155

Validation System

ValidatedDTO uses ValidatorFactoryInterface from Hyperf's validation component:


Sources: src/validated-dto/src/ValidatedDTO.php148-164

ConfigProvider Registration

The component registers itself via ConfigProvider:


This enables automatic discovery and integration with Hyperf's DI container.

Sources: src/validated-dto/composer.json47-49