コンテンツにスキップ

XOOPSのリポジトリパターン

2.5.x ✅ 4.0.x ✅

リポジトリパターンはデータベース操作を抽象化し、データアクセスのクリーンなインターフェースを提供するデータアクセスパターンです。ビジネスロジックとデータマッピングレイヤー間の中間者として機能します。

リポジトリパターンは以下を提供します:

  • データベース実装の詳細を抽象化
  • ユニットテストのための簡単なモック
  • データアクセスロジックの一元化
  • ビジネスロジックに影響を与えずにデータベースを変更する柔軟性
  • アプリケーション全体で再利用可能なデータアクセスロジック

リポジトリを使用する場合:

  • アプリケーションレイヤー間でデータを転送するとき
  • データベース実装を変更する必要があるとき
  • モックを使用してテストしやすいコードを記述するとき
  • データアクセスパターンを抽象化するとき
<?php
// リポジトリインターフェースを定義
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);
}
// リポジトリを実装
class UserRepository implements UserRepositoryInterface
{
private $db;
public function __construct($connection)
{
$this->db = $connection;
}
public function find($id)
{
// 実装
}
public function save($entity)
{
// 実装
}
}
?>
<?php
class UserService
{
private $userRepository;
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
public function registerUser($username, $email, $password)
{
// ユーザーが存在するか確認
if ($this->userRepository->findByUsername($username)) {
throw new \InvalidArgumentException('ユーザー名は既に存在します');
}
// ユーザーを作成
$user = new User();
$user->setUsername($username);
$user->setEmail($email);
$user->setPassword($password);
return $this->userRepository->save($user);
}
}
?>
  • インターフェースを使用してリポジトリ契約を定義
  • 各リポジトリはエンティティ型を1つ処理
  • ビジネスロジックをサービスに保つ、リポジトリには保たない
  • エンティティオブジェクトを使用してデータマッピング
  • 無効な操作に対して適切な例外をスロー

関連トピック:


タグ: #repository-pattern #data-access #design-patterns #module-development