Nâng CaoLaravel iconLaravel

DTOs (Data Transfer Objects) là gì và cách cải thiện kiến trúc code?

DTO là các value object đơn giản đóng gói dữ liệu request/response không có business logic, đảm bảo type safety.

Ví dụ: class CreateUserDTO { public function __construct(public string $name, public string $email, public int $age) {} }.

Lợi ích: type hinting rõ ràng thay vì unpack array mù quáng, bắt lỗi type tại compile time, self-document tham số mong muốn, IDE autocomplete đầy đủ, dễ refactor qua nhiều controller/service. Phân biệt với Eloquent model (entity DB có ORM logic). Với PHP 8.2+ readonly class, DTO trở nên bất biến và an toàn hơn: readonly class CreateUserDTO { ... }.

Xem toàn bộ Laravel cùng filter theo level & chủ đề con.

Mở danh sách Laravel