存储库中的多个数据库表 - 如何做到这一点?

Multiple DB-Tables in Repository - How to do this?

我有以下代码:

控制器

class UserController {
    
    public function __construct(userRepository $userRepository) {
        $this->userRepository = $userRepository;
    }
[...]

存储库

class UserRepository extends AbstractRepository {

    public function getTablename() {
        return "tbl_users";
    }

    public function getModel() {
        return "administration\CMR\UserModel";
    }
[...]

抽象知识库

abstract class AbstractRepository {
    
    protected $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }
    
    abstract public function getTablename();
    abstract public function getModel();
    
    function readAll() {
        
        $table = $this->getTablename();
        $model = $this->getModel();
        
        $stmt = $this->pdo->query("SELECT * FROM $table");
        $res = $stmt->fetchAll(PDO::FETCH_CLASS, $model);
        return $res;
    }
[...]

我的问题是,一个查询需要“tbl_users”,另一个查询需要第二个 table (tbl_locations)。谁能解释一下如何做到这一点?我认为没有必要再次编写相同的 readAll()-Function only with other variable.

如果我没理解错的话,您希望能够根据自己的喜好设置表名。一种可能是在 UserRepository 构造函数中传递一个表名(并设置一个默认值),如下所示:

class UserRepository extends AbstractRepository {

    public function getTablename() {
        return $this->tablename;
    }

    public function getModel() {
        return "administration\CMR\UserModel";
    }
    [...]



abstract class AbstractRepository {
    
    protected $pdo;
    protected $tablename;

    public function __construct(PDO $pdo, string $tablename = "tbl_users") {
        $this->pdo = $pdo;
        $this->tablename = $tablename;
    }
    
    abstract public function getTablename();
    abstract public function getModel();
    
    function readAll() {
        
        $table = $this->getTablename();
        $model = $this->getModel();
        
        $stmt = $this->pdo->query("SELECT * FROM $table");
        $res = $stmt->fetchAll(PDO::FETCH_CLASS, $model);
        return $res;
    }
    [...]

从添加位置存储库开始

class LocationRepository extends AbstractRepository implements LocationRepositoryInterface {

    public function getTablename() {
        return "tbl_locations";
    }

    public function getModel() {
        return "administration\CMR\LocationModel";
    }
[...]

并将两个存储库都放到上层,比如UserLocationService

class UserLocationService implements UserLocationInterface {
    public function __construct(
        protected UserRepositoryInterface $userRepository,
        protected LocationRepositoryInterface $locationRepository
    ) {
    }

[...]
}

通过这种方式,您可以为用户和位置提供单独的存储库,但您可以在需要两个存储库来实现其逻辑的服务中对两者进行操作。