Serialization
Learn how to serialize DTOs to arrays, JSON, XML, and other formats.
What is Serialization?
Section titled “What is Serialization?”Serialization converts DTOs to different formats for storage or transmission:
$dto = new UserDTO(name: 'John Doe', email: 'john@example.com');
// To array$array = $dto->toArray();
// To JSON$json = json_encode($dto);
// To XML$xml = $dto->toXml();To Array
Section titled “To Array”Basic Usage
Section titled “Basic Usage”$dto = UserDTO::fromArray([ 'name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30,]);
$array = $dto->toArray();// ['name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30]Nested DTOs
Section titled “Nested DTOs”$dto = UserDTO::fromArray([ 'name' => 'John Doe', 'address' => [ 'street' => '123 Main St', 'city' => 'New York', ],]);
$array = $dto->toArray();// [// 'name' => 'John Doe',// 'address' => [// 'street' => '123 Main St',// 'city' => 'New York',// ],// ]To JSON
Section titled “To JSON”Basic Usage
Section titled “Basic Usage”$dto = new UserDTO(name: 'John Doe', email: 'john@example.com');
$json = json_encode($dto);// {"name":"John Doe","email":"john@example.com"}Pretty Print
Section titled “Pretty Print”$json = json_encode($dto, JSON_PRETTY_PRINT);// {// "name": "John Doe",// "email": "john@example.com"// }Using toJson()
Section titled “Using toJson()”$json = $dto->toJson();// {"name":"John Doe","email":"john@example.com"}
$json = $dto->toJson(JSON_PRETTY_PRINT);// Pretty printed JSONTo XML
Section titled “To XML”Basic Usage
Section titled “Basic Usage”$dto = new UserDTO(name: 'John Doe', email: 'john@example.com');
$xml = $dto->toXml();// <?xml version="1.0"?>// <user>// <name>John Doe</name>// <email>john@example.com</email>// </user>Custom Root Element
Section titled “Custom Root Element”$xml = $dto->toXml(rootElement: 'customer');// <?xml version="1.0"?>// <customer>// <name>John Doe</name>// <email>john@example.com</email>// </customer>To YAML
Section titled “To YAML”Basic Usage
Section titled “Basic Usage”$dto = new UserDTO(name: 'John Doe', email: 'john@example.com');
$yaml = $dto->toYaml();// name: John Doe// email: john@example.comTo CSV
Section titled “To CSV”Basic Usage
Section titled “Basic Usage”$dto = new UserDTO(name: 'John Doe', email: 'john@example.com');
$csv = $dto->toCsv();// "name","email"// "John Doe","john@example.com"Collection to CSV
Section titled “Collection to CSV”$users = UserDTO::collection($userArray);$csv = $users->toCsv();Conditional Serialization
Section titled “Conditional Serialization”With Conditional Attributes
Section titled “With Conditional Attributes”class UserDTO extends SimpleDTO{ public function __construct( public readonly string $name,
#[WhenAuth] public readonly ?string $email = null,
#[WhenCan('view-admin')] public readonly ?array $adminData = null, ) {}}
// Only includes properties based on conditions$array = $dto->toArray();With Hidden Attribute
Section titled “With Hidden Attribute”class UserDTO extends SimpleDTO{ public function __construct( public readonly string $name,
#[Hidden] public readonly string $password, ) {}}
$array = $dto->toArray();// ['name' => 'John Doe']// password is excludedCustom Serialization
Section titled “Custom Serialization”Override toArray()
Section titled “Override toArray()”class UserDTO extends SimpleDTO{ public function __construct( public readonly string $firstName, public readonly string $lastName, ) {}
public function toArray(): array { return [ 'full_name' => $this->firstName . ' ' . $this->lastName, ]; }}Custom Serializer
Section titled “Custom Serializer”class UserDTO extends SimpleDTO{ public function toCustomFormat(): array { return [ 'user' => [ 'name' => $this->name, 'contact' => [ 'email' => $this->email, ], ], ]; }}Best Practices
Section titled “Best Practices”Use Appropriate Format
Section titled “Use Appropriate Format”// ✅ Good - use appropriate format$json = $dto->toJson(); // For APIs$xml = $dto->toXml(); // For XML APIs$csv = $dto->toCsv(); // For exportsHandle Sensitive Data
Section titled “Handle Sensitive Data”// ✅ Good - hide sensitive data#[Hidden]public readonly string $password;
// ❌ Bad - expose sensitive datapublic readonly string $password;Use Conditional Attributes
Section titled “Use Conditional Attributes”// ✅ Good - conditional serialization#[WhenAuth]public readonly ?string $email;
// ❌ Bad - always includepublic readonly string $email;Code Examples
Section titled “Code Examples”The following working examples demonstrate this feature:
- Serializers - Serialization examples
- Transformers - Data transformation
- Normalizers - Data normalization
- Serializer Options - Customizing serialization
All examples are fully tested and can be run directly.
Related Tests
Section titled “Related Tests”The functionality is thoroughly tested. Key test files:
- SerializationTest.php - Serialization tests
Run the tests:
# Run teststask test:unit -- --filter=SerializationSee Also
Section titled “See Also”- Conditional Properties - Dynamic visibility
- Security & Visibility - Control data exposure
- Type Casting - Automatic type conversion