Skip to content

Serialization

Learn how to serialize Dtos to arrays, JSON, XML and other formats.

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();
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]

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']]
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',
// ],
// ]
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"}
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 JSON
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}
use Tests\Utils\Docu\Dtos\UserDto;
$dto = new UserDto(name: 'John Doe', email: 'john@example.com');
$xml = $dto->toXml();
// Returns XML string with user data
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 element
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.com
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,
use Tests\Utils\Docu\Dtos\UserDto;
$users = UserDto::collection($userArray);
$csv = $users->toCsv();
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();
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 excluded
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,
];
}
}
use event4u\DataHelpers\SimpleDto;
class UserDto extends SimpleDto
{
public function toCustomFormat(): array
{
return [
'user' => [
'name' => $this->name,
'contact' => [
'email' => $this->email,
],
],
];
}
}
// ✅ Good - use appropriate format
$json = $dto->toJson(); // For APIs
$xml = $dto->toXml(); // For XML APIs
$csv = $dto->toCsv(); // For exports
// ✅ Good - hide sensitive data
#[Hidden]
public readonly string $password;
// ❌ Bad - expose sensitive data
public readonly string $password;
// ✅ Good - conditional serialization
#[WhenAuth]
public readonly ?string $email;
// ❌ Bad - always include
public readonly string $email;

The following working examples demonstrate this feature:

All examples are fully tested and can be run directly.

The functionality is thoroughly tested. Key test files:

Run the tests:

Terminal window
# Run tests
task test:unit -- --filter=Serialization