Bỏ qua để đến nội dung

Mẫu DTO trong XOOPS

DTO Mẫu (Đối tượng truyền dữ liệu) trong XOOPS

Phần tiêu đề “DTO Mẫu (Đối tượng truyền dữ liệu) trong XOOPS”

2.5.x ✅ 4.0.x ✅

Đối tượng truyền dữ liệu (DTO) là các đối tượng đơn giản được sử dụng để truyền dữ liệu giữa các lớp khác nhau của ứng dụng. DTO giúp duy trì ranh giới rõ ràng giữa các lớp và giảm sự phụ thuộc vào các đối tượng thực thể.

DTO là:

  • Một đối tượng giá trị đơn giản với các thuộc tính
  • Không thay đổi hoặc chỉ đọc sau khi tạo
  • Không có logic hoặc phương thức kinh doanh
  • Tối ưu hóa để truyền dữ liệu
  • Độc lập với cơ chế kiên trì

Sử dụng DTO khi:

  • Truyền dữ liệu giữa các lớp
  • Hiển thị dữ liệu thông qua API
  • Tổng hợp dữ liệu từ nhiều thực thể
  • Ẩn chi tiết triển khai nội bộ
  • Thay đổi cấu trúc dữ liệu cho những người tiêu dùng khác nhau
<?php
class UserDTO
{
private $id;
private $username;
private $email;
private $isActive;
private $createdAt;
public function __construct($entity = null)
{
if ($entity instanceof User) {
$this->id = $entity->getId();
$this->username = $entity->getUsername();
$this->email = $entity->getEmail();
$this->isActive = $entity->isActive();
$this->createdAt = $entity->getCreatedAt();
}
}
// Read-only accessors
public function getId() { return $this->id; }
public function getUsername() { return $this->username; }
public function getEmail() { return $this->email; }
public function isActive() { return $this->isActive; }
public function getCreatedAt() { return $this->createdAt; }
public function toArray()
{
return [
'id' => $this->id,
'username' => $this->username,
'email' => $this->email,
'isActive' => $this->isActive,
'createdAt' => $this->createdAt,
];
}
public function toJson()
{
return json_encode($this->toArray());
}
}
?>
<?php
class CreateUserRequestDTO
{
private $username;
private $email;
private $password;
private $errors = [];
public function __construct(array $data)
{
$this->username = $data['username'] ?? '';
$this->email = $data['email'] ?? '';
$this->password = $data['password'] ?? '';
$this->validate();
}
private function validate()
{
if (empty($this->username) || strlen($this->username) < 3) {
$this->errors['username'] = 'Username too short';
}
if (empty($this->email) || !filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = 'Invalid email';
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = 'Password too short';
}
}
public function isValid()
{
return empty($this->errors);
}
public function getErrors()
{
return $this->errors;
}
public function getUsername() { return $this->username; }
public function getEmail() { return $this->email; }
public function getPassword() { return $this->password; }
}
?>
<?php
class UserService
{
public function createUserFromRequest(CreateUserRequestDTO $dto)
{
if (!$dto->isValid()) {
throw new ValidationException('Invalid input', $dto->getErrors());
}
$user = new User();
$user->setUsername($dto->getUsername());
$user->setEmail($dto->getEmail());
$user->setPassword($dto->getPassword());
$userId = $this->userRepository->save($user);
return new UserDTO($user);
}
}
?>
<?php
class ApiController
{
public function createUserAction()
{
$input = json_decode(file_get_contents('php://input'), true);
$dto = new CreateUserRequestDTO($input);
if (!$dto->isValid()) {
http_response_code(400);
return ['success' => false, 'errors' => $dto->getErrors()];
}
try {
$userDTO = $this->userService->createUserFromRequest($dto);
http_response_code(201);
return ['success' => true, 'data' => $userDTO->toArray()];
} catch (\Exception $e) {
http_response_code(500);
return ['success' => false, 'message' => $e->getMessage()];
}
}
}
?>
  • Giữ DTO tập trung và cụ thể
  • Làm cho DTO trở nên bất biến hoặc chỉ đọc
  • Không logic kinh doanh include trong DTO
  • Sử dụng DTO riêng biệt cho đầu vào và đầu ra
  • Ghi rõ thuộc tính DTO
  • Giữ DTO đơn giản - chỉ là nơi chứa dữ liệu

Xem thêm:


Tags: #dto #data-transfer-objects #design-patterns #module-development