Class DtoMapper
Maps array data to DTO objects using reflection.
This mapper enables the projectAs() query method to hydrate results
directly into DTO objects instead of entities. It uses PHP 8 features:
- Type hints on constructor parameters to detect nested DTOs
- #[CollectionOf] attribute to specify DTO type for array collections
- Named arguments for construction
Example DTO
readonly class UserDto {
public function __construct(
public int $id,
public string $username,
public ?RoleDto $role = null,
#[CollectionOf(CommentDto::class)]
public array $comments = [],
) {}
}
Usage with Query
$users = $this->Users->find()
->contain(['Roles', 'Comments'])
->projectAs(UserDto::class)
->all();
Namespace: Cake\ORM
Property Summary
-
$cache protected static
array<string, array{params: array<string, array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: (class-string|null, collectionOf: (class-string|null)}>}>Cached reflection info per class.
Method Summary
-
analyzeParameter() protected
Analyze a constructor parameter for DTO mapping info.
-
clearCache() public static
Clear the reflection cache.
-
getClassInfo() protected
Get cached class info via reflection.
-
map() public
Map array data to a DTO instance.
Method Detail
analyzeParameter() ¶ protected
analyzeParameter(ReflectionParameter $param): array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: (class-string|null, collectionOf: (class-string|null)}
Analyze a constructor parameter for DTO mapping info.
Parameters
-
ReflectionParameter$param The parameter to analyze
Returns
array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: (class-string|null, collectionOf: (class-string|null)}clearCache() ¶ public static
clearCache(): void
Clear the reflection cache.
Useful for testing or when classes are reloaded.
Returns
voidgetClassInfo() ¶ protected
getClassInfo(class-string $class): array{params: array<string, array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: (class-string|null, collectionOf: (class-string|null)}>}
Get cached class info via reflection.
Parameters
-
class-string$class The class to analyze
Returns
array{params: array<string, array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: (class-string|null, collectionOf: (class-string|null)}>}map() ¶ public
map(array<string, mixed> $data, class-string<T> $dtoClass): T
Map array data to a DTO instance.
Templates
T
of object Parameters
-
array<string, mixed>$data The source data (typically from ORM)
-
class-string<T>$dtoClass The target DTO class
Returns
TProperty Detail
$cache ¶ protected static
Cached reflection info per class.
Type
array<string, array{params: array<string, array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: (class-string|null, collectionOf: (class-string|null)}>}>