
本文介绍通过面向接口的仓储模式设计,让抽象仓储类支持多种数据表,避免重复代码;核心是为每张表创建独立仓储实现类,并在服务层组合使用。
本文介绍通过面向接口的仓储模式设计,让抽象仓储类支持多种数据表,避免重复代码;核心是为每张表创建独立仓储实现类,并在服务层组合使用。
在分层架构(如 MVC 或 Clean Architecture)中,仓储(Repository)模式常用于解耦业务逻辑与数据访问细节。但当系统需操作多张结构差异较大或职责分离明确的数据表(如 tbl_users 和 tbl_locations)时,强行将所有查询塞入一个仓储类会导致违反单一职责原则,也难以维护。
正确的做法是:为每张核心业务表定义专属的仓储实现类,复用统一的抽象基类,再通过服务层(Service)协调多个仓储协作。这既保持了代码复用性,又确保了职责清晰。
✅ 推荐实现方式
首先,确保你的抽象仓储已定义好可扩展契约:
abstract class AbstractRepository
{
protected PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
abstract public function getTablename(): string;
abstract public function getModel(): string;
public function readAll(): array
{
$table = $this->getTablename();
$model = $this->getModel();
$stmt = $this->pdo->query("SELECT * FROM `$table`");
return $stmt->fetchAll(PDO::FETCH_CLASS, $model);
}
public function findById(int $id): ?object
{
$table = $this->getTablename();
$model = $this->getModel();
$stmt = $this->pdo->prepare("SELECT * FROM `$table` WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetchObject($model);
}
}? 提示:使用反引号包裹表名可防止 SQL 关键字冲突;findById 等通用方法也应放在抽象类中,进一步减少重复。
接着,为每张表创建具体仓储类——它们仅需专注自身表名与模型映射:
// UserRepository.php
class UserRepository extends AbstractRepository implements UserRepositoryInterface
{
public function getTablename(): string
{
return 'tbl_users';
}
public function getModel(): string
{
return 'administration\CMR\UserModel';
}
}
// LocationRepository.php
class LocationRepository extends AbstractRepository implements LocationRepositoryInterface
{
public function getTablename(): string
{
return 'tbl_locations';
}
public function getModel(): string
{
return 'administration\CMR\LocationModel';
}
}最后,在应用逻辑层(如 Service)中注入所需仓储,按需调用:
class UserLocationService implements UserLocationServiceInterface
{
public function __construct(
private readonly UserRepositoryInterface $userRepository,
private readonly LocationRepositoryInterface $locationRepository
) {}
public function getUserWithLocation(int $userId): array
{
$user = $this->userRepository->findById($userId);
if (!$user) {
throw new RuntimeException('User not found');
}
// 假设 UserModel 有 location_id 属性
$location = $this->locationRepository->findById($user->location_id ?? 0);
return [
'user' => $user,
'location' => $location,
];
}
}⚠️ 注意事项与最佳实践
- 接口先行:为每个仓储定义接口(如 UserRepositoryInterface),便于依赖注入与单元测试模拟;
- 避免跨表通用方法:不要在 AbstractRepository 中添加 joinUsersAndLocations() 这类强耦合方法——它属于服务或查询对象(Query Object)的职责;
- 考虑查询性能:若高频联合查询,可额外提供专用的 UserLocationQuery 类,封装原生 SQL 或构建器逻辑,而非污染仓储;
- 命名一致性:仓储类名建议与表名/领域实体对齐(如 LocationRepository → tbl_locations),降低认知成本;
- 事务管理:涉及多仓储写操作时,应在 Service 层统一开启 PDO 事务,而非分散在各仓储中。
通过这种“一表一仓储 + 抽象复用 + 服务编排”的模式,你既能享受 OOP 的可维护性与可测试性,又能灵活应对复杂的数据访问场景,真正践行关注点分离的设计哲学。

















