Mapping Attributes
Reference for property mapping attributes.
Introduction
Section titled “Introduction”SimpleDTO provides 2 mapping attributes:
- #[MapFrom(string $source)] - Map from different input key
- #[MapTo(string $target)] - Map to different output key
MapFrom Attribute
Section titled “MapFrom Attribute”Map input data from a different key:
use Event4u\DataHelpers\SimpleDTO\Attributes\MapFrom;
#[MapFrom('full_name')]public readonly string $name;
#[MapFrom('email_address')]public readonly string $email;Nested Path Mapping
Section titled “Nested Path Mapping”#[MapFrom('contact.email')]public readonly string $email;
#[MapFrom('address.city.name')]public readonly string $city;Multiple Sources (Fallback)
Section titled “Multiple Sources (Fallback)”#[MapFrom(['user.email', 'user.mail', 'email'])]public readonly string $email;MapTo Attribute
Section titled “MapTo Attribute”Map output data to a different key:
use Event4u\DataHelpers\SimpleDTO\Attributes\MapTo;
#[MapTo('full_name')]public readonly string $name;
#[MapTo('email_address')]public readonly string $email;Nested Output
Section titled “Nested Output”#[MapTo('user.profile.email')]public readonly string $email;// Output: ['user' => ['profile' => ['email' => '...']]]Bidirectional Mapping
Section titled “Bidirectional Mapping”#[MapFrom('user_name'), MapTo('user_name')]public readonly string $userName;Real-World Examples
Section titled “Real-World Examples”API Response Mapping
Section titled “API Response Mapping”class UserDTO extends SimpleDTO{ public function __construct( #[MapFrom('user_id')] public readonly int $id,
#[MapFrom('user_name')] public readonly string $name,
#[MapFrom('user_email')] public readonly string $email, ) {}}Database Column Mapping
Section titled “Database Column Mapping”class OrderDTO extends SimpleDTO{ public function __construct( #[MapFrom('order_id')] public readonly int $id,
#[MapFrom('customer_name')] public readonly string $customerName, ) {}}Combining with Other Attributes
Section titled “Combining with Other Attributes”// MapFrom + Validation#[MapFrom('user_email'), Required, Email]public readonly string $email;
// MapFrom + Cast#[MapFrom('created_at'), Cast(DateTimeCast::class)]public readonly Carbon $createdAt;Best Practices
Section titled “Best Practices”Use Descriptive Property Names
Section titled “Use Descriptive Property Names”// ✅ Good#[MapFrom('usr_nm')]public readonly string $userName;
// ❌ Bad#[MapFrom('usr_nm')]public readonly string $usrNm;See Also
Section titled “See Also”- Property Mapping - Detailed guide
- Validation Attributes - Validation reference