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:
use Tests\Utils\Docu\Dtos\UserDto;
$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”use Tests\Utils\Docu\Dtos\UserDto;
$dto = UserDto::fromArray([ 'name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30,]);
$array = $dto->toArray();// ['name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30]With Context
Section titled “With Context”Pass context for conditional properties:
use event4u\DataHelpers\SimpleDto;use event4u\DataHelpers\SimpleDto\Attributes\WhenContext;
class UserDto extends SimpleDto{ public function __construct( public readonly string $name, public readonly string $email,
#[WhenContext('includeDebug')] public readonly ?array $debugInfo = null, ) {}}
$dto = UserDto::fromArray([ 'name' => 'John Doe', 'email' => 'john@example.com', 'debugInfo' => ['created_at' => '2024-01-01'],]);
// Without context - debugInfo excluded$array = $dto->toArray();// ['name' => 'John Doe', 'email' => 'john@example.com']
// With context - debugInfo included$array = $dto->toArray(['includeDebug' => true]);// ['name' => 'John Doe', 'email' => 'john@example.com', 'debugInfo' => ['created_at' => '2024-01-01']]Nested Dtos
Section titled “Nested Dtos”use Tests\Utils\Docu\Dtos\UserDto;
$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”use Tests\Utils\Docu\Dtos\UserDto;
$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”use Tests\Utils\Docu\Dtos\UserDto;
$dto = new UserDto(name: 'John Doe', email: 'john@example.com');$json = json_encode($dto, JSON_PRETTY_PRINT);// $json contains pretty-printed JSONUsing toJson()
Section titled “Using toJson()”use Tests\Utils\Docu\Dtos\UserDto;
$dto = new UserDto(name: 'John Doe', email: 'john@example.com');$json = $dto->toJson();// Result: {"name":"John Doe","email":"john@example.com","age":0,"address":null}To XML
Section titled “To XML”Basic Usage
Section titled “Basic Usage”use Tests\Utils\Docu\Dtos\UserDto;
$dto = new UserDto(name: 'John Doe', email: 'john@example.com');
$xml = $dto->toXml();// Returns XML string with user dataCustom Root Element
Section titled “Custom Root Element”use event4u\DataHelpers\SimpleDto\Config\SerializerOptions;use Tests\Utils\Docu\Dtos\UserDto;
$dto = new UserDto(name: 'John Doe', email: 'john@example.com');$options = SerializerOptions::xml(rootElement: 'customer');$xml = $dto->toXml($options);// $xml contains XML with <customer> root elementTo YAML
Section titled “To YAML”Basic Usage
Section titled “Basic Usage”use Tests\Utils\Docu\Dtos\UserDto;
$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”use Tests\Utils\Docu\Dtos\UserDto;
$dto = new UserDto(name: 'John Doe', email: 'john@example.com');
$csv = $dto->toCsv();// Result: name,email,age,address// "John Doe",john@example.com,0,Collection to CSV
Section titled “Collection to CSV”use Tests\Utils\Docu\Dtos\UserDto;
$users = UserDto::collection($userArray);$csv = $users->toCsv();Conditional Serialization
Section titled “Conditional Serialization”With Conditional Attributes
Section titled “With Conditional Attributes”use event4u\DataHelpers\SimpleDto;
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”use event4u\DataHelpers\SimpleDto;
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()”use event4u\DataHelpers\SimpleDto;
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”use event4u\DataHelpers\SimpleDto;
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