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

Mẫu lưu trữ trong XOOPS

2.5.x ✅ 4.0.x ✅

Mẫu lưu trữ là mẫu truy cập dữ liệu trừu tượng hóa các hoạt động cơ sở dữ liệu, cung cấp giao diện rõ ràng để truy cập dữ liệu. Nó hoạt động như một người trung gian giữa logic nghiệp vụ và các lớp ánh xạ dữ liệu.

Mẫu Kho lưu trữ cung cấp:

  • Tóm tắt chi tiết triển khai cơ sở dữ liệu
  • Dễ dàng mô phỏng để kiểm tra đơn vị
  • Logic truy cập dữ liệu tập trung
  • Linh hoạt thay đổi cơ sở dữ liệu mà không ảnh hưởng đến logic nghiệp vụ
  • Logic truy cập dữ liệu có thể tái sử dụng trên ứng dụng

Sử dụng Kho lưu trữ khi:

  • Truyền dữ liệu giữa các lớp ứng dụng
  • Cần thay đổi việc thực hiện cơ sở dữ liệu
  • Viết mã có thể kiểm tra được bằng mock
  • Tóm tắt các mô hình truy cập dữ liệu
<?php
// Define repository interface
interface UserRepositoryInterface
{
public function find($id);
public function findAll($limit = null, $offset = 0);
public function findBy(array $criteria);
public function save($entity);
public function update($id, $entity);
public function delete($id);
}
// Implement repository
class UserRepository implements UserRepositoryInterface
{
private $db;
public function __construct($connection)
{
$this->db = $connection;
}
public function find($id)
{
// Implementation
}
public function save($entity)
{
// Implementation
}
}
?>
<?php
class UserService
{
private $userRepository;
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
public function registerUser($username, $email, $password)
{
// Check if user exists
if ($this->userRepository->findByUsername($username)) {
throw new \InvalidArgumentException('Username exists');
}
// Create user
$user = new User();
$user->setUsername($username);
$user->setEmail($email);
$user->setPassword($password);
return $this->userRepository->save($user);
}
}
?>
  • Sử dụng giao diện để xác định hợp đồng kho lưu trữ
  • Mỗi kho lưu trữ xử lý một loại thực thể
  • Giữ logic kinh doanh trong các dịch vụ, không phải kho lưu trữ
  • Sử dụng các đối tượng thực thể để ánh xạ dữ liệu
  • Ném ra ngoại lệ thích hợp cho các hoạt động không hợp lệ

Xem thêm:


Tags: #repository-pattern #data-access #design-patterns #module-development