DTOs use typed, explicit fields to transfer validated values between layers.
What It Does
DTOs use typed, explicit fields to transfer validated values between layers. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
final class UserDto { public function __construct(public readonly int $id, public readonly string $email) {} }
print_r(new UserDto(5, '[email protected]'));
Example 2: Another Case
Examine the edge case and the observable result.
<?php
final class ProductDto { public function __construct(public readonly string $sku, public readonly int $priceCents) { if ($priceCents < 0) throw new InvalidArgumentException('Negative price'); } }
echo (new ProductDto('P01', 250))->sku;
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
final class ResponseDto { public function __construct(public readonly string $status, public readonly array $items) {} public function json(): string { return json_encode(['status' => $this->status, 'items' => $this->items], JSON_THROW_ON_ERROR); } }
echo (new ResponseDto('ok', [1,2]))->json();
Important Behavior and Edge Cases
A public readonly field prevents reassignment, not mutation of a referenced object inside it.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Creating DTOs with Typed Properties | DTOs use typed, explicit fields to transfer validated values between layers. |
| Related approach | Keep business validation in dedicated constructors or domain objects. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Creating DTOs with Typed Properties | A public readonly field prevents reassignment, not mutation of a referenced object inside it. |
| Assuming a related mechanism has the same behavior | Keep business validation in dedicated constructors or domain objects. |
Key Takeaways
- DTOs use typed, explicit fields to transfer validated values between layers.
- A public readonly field prevents reassignment, not mutation of a referenced object inside it.
- Keep business validation in dedicated constructors or domain objects.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.