前言:我试图在关系数据库的MVC架构中使用存储库模式。

我最近开始学习PHP中的TDD,我意识到我的数据库与应用程序的其余部分耦合得太紧密了。我读过关于存储库和使用IoC容器将其“注入”到控制器的文章。非常酷的东西。但是现在有一些关于存储库设计的实际问题。考虑下面的例子。

<?php

class DbUserRepository implements UserRepositoryInterface
{
    protected $db;

    public function __construct($db)
    {
        $this->db = $db;
    }

    public function findAll()
    {
    }

    public function findById($id)
    {
    }

    public function findByName($name)
    {
    }

    public function create($user)
    {
    }

    public function remove($user)
    {
    }

    public function update($user)
    {
    }
}

问题#1:字段太多

所有这些查找方法都使用select所有字段(select *)方法。然而,在我的应用程序中,我总是试图限制我获得的字段数量,因为这通常会增加开销并降低速度。对于使用这种模式的用户,如何处理这种情况?

问题2:方法太多

虽然这个类现在看起来不错,但我知道在真实的应用程序中,我需要更多的方法。例如:

findAllByNameAndStatus findAllInCountry findAllWithEmailAddressSet findAllByAgeAndGender findAllByAgeAndGenderOrderByAge 等。

如你所见,可能有一个非常非常长的方法列表。然后,如果您添加了上述字段选择问题,问题就会恶化。在过去,我通常只是把所有这些逻辑放在我的控制器中:

<?php

class MyController
{
    public function users()
    {
        $users = User::select('name, email, status')
            ->byCountry('Canada')->orderBy('name')->rows();

        return View::make('users', array('users' => $users));
    }
}

使用我的存储库方法,我不想以这样的结果结束:

<?php

class MyController
{
    public function users()
    {
        $users = $this->repo->get_first_name_last_name_email_username_status_by_country_order_by_name('Canada');

        return View::make('users', array('users' => $users))
    }

}

问题3:不可能匹配接口

I see the benefit in using interfaces for repositories, so I can swap out my implementation (for testing purposes or other). My understanding of interfaces is that they define a contract that an implementation must follow. This is great until you start adding additional methods to your repositories like findAllInCountry(). Now I need to update my interface to also have this method, otherwise, other implementations may not have it, and that could break my application. By this feels insane...a case of the tail wagging the dog.

规范模式吗?

这让我相信存储库应该只有固定数量的方法(如save()、remove()、find()、findAll()等)。但是如何运行特定的查找呢?我听说过规范模式,但在我看来,这只减少了整个记录集(通过IsSatisfiedBy()),如果从数据库提取,这显然有主要的性能问题。

帮助吗?

显然,在使用存储库时,我需要重新考虑一些事情。有谁能告诉我这个最好怎么处理吗?


当前回答

Issue #3: Impossible to match an interface I see the benefit in using interfaces for repositories, so I can swap out my implementation (for testing purposes or other). My understanding of interfaces is that they define a contract that an implementation must follow. This is great until you start adding additional methods to your repositories like findAllInCountry(). Now I need to update my interface to also have this method, otherwise, other implementations may not have it, and that could break my application. By this feels insane...a case of the tail wagging the dog.

我的直觉告诉我,这可能需要一个实现查询优化方法和泛型方法的接口。对性能敏感的查询应该有针对性的方法,而不频繁或轻量级的查询则由通用处理程序处理,这可能会使控制器做更多的杂耍。

泛型方法将允许实现任何查询,因此将防止在过渡期间发生破坏性更改。目标方法允许您在有意义时优化调用,并且它可以应用于多个服务提供者。

这种方法类似于硬件实现执行特定的优化任务,而软件实现只做简单的工作或灵活的实现。

其他回答

我只能对我们(在我的公司)处理此事的方式发表评论。首先,性能对我们来说不是太大的问题,但拥有干净/适当的代码才是。

首先,我们定义模型,例如使用ORM创建UserEntity对象的UserModel。当一个UserEntity从一个模型中加载时,所有字段都被加载。对于引用外部实体的字段,我们使用适当的外部模型来创建各自的实体。对于这些实体,数据将按需加载。现在你的第一反应可能是…??? !!让我给你们举个例子一个小例子

class UserEntity extends PersistentEntity
{
    public function getOrders()
    {
        $this->getField('orders'); //OrderModel creates OrderEntities with only the ID's set
    }
}

class UserModel {
    protected $orm;

    public function findUsers(IGetOptions $options = null)
    {
        return $orm->getAllEntities(/*...*/); // Orm creates a list of UserEntities
    }
}

class OrderEntity extends PersistentEntity {} // user your imagination
class OrderModel
{
    public function findOrdersById(array $ids, IGetOptions $options = null)
    {
        //...
    }
}

In our case $db is an ORM that is able to load entities. The model instructs the ORM to load a set of entities of a specific type. The ORM contains a mapping and uses that to inject all the fields for that entity in to the entity. For foreign fields however only the id's of those objects are loaded. In this case the OrderModel creates OrderEntitys with only the id's of the referenced orders. When PersistentEntity::getField gets called by the OrderEntity the entity instructs it's model to lazy load all the fields into the OrderEntitys. All the OrderEntitys associated with one UserEntity are treated as one result-set and will be loaded at once.

这里的神奇之处在于,我们的模型和ORM将所有数据注入到实体中,而实体只是为PersistentEntity提供的通用getField方法提供包装器函数。总而言之,我们总是加载所有的字段,但引用外部实体的字段在必要时才加载。仅仅加载一堆字段并不是真正的性能问题。然而,加载所有可能的外国实体将是一个巨大的性能下降。

现在,根据where子句加载一组特定的用户。我们提供了一个面向对象的类包,允许您指定可以粘在一起的简单表达式。在示例代码中,我将其命名为GetOptions。它是一个选择查询的所有可能选项的包装器。它包含where子句、group by子句和其他所有内容的集合。我们的where子句相当复杂,但你显然可以很容易地做出一个更简单的版本。

$objOptions->getConditionHolder()->addConditionBind(
    new ConditionBind(
        new Condition('orderProduct.product', ICondition::OPERATOR_IS, $argObjProduct)
    )
);

该系统最简单的版本是将查询的WHERE部分作为字符串直接传递给模型。

我很抱歉回答这么复杂。我试着尽可能快速和清晰地总结我们的框架。如果你有任何其他问题,请随时问他们,我会更新我的答案。

编辑:另外,如果你真的不想马上加载某些字段,你可以在ORM映射中指定一个延迟加载选项。因为所有字段最终都是通过getField方法加载的,所以当调用该方法时,您可以在最后一分钟加载一些字段。这在PHP中不是一个很大的问题,但我不建议其他系统也这样做。

这是我见过的一些不同的解决方案。每一种都有利弊,但这是由你来决定的。

问题#1:字段太多

This is an important aspect especially when you take in to account Index-Only Scans. I see two solutions to dealing with this problem. You can update your functions to take in an optional array parameter that would contain a list of a columns to return. If this parameter is empty you'd return all of the columns in the query. This can be a little weird; based off the parameter you could retrieve an object or an array. You could also duplicate all of your functions so that you have two distinct functions that run the same query, but one returns an array of columns and the other returns an object.

public function findColumnsById($id, array $columns = array()){
    if (empty($columns)) {
        // use *
    }
}

public function findById($id) {
    $data = $this->findColumnsById($id);
}

问题2:方法太多

一年前,我曾短暂地与Propel ORM合作过,这是基于我对那次经历的记忆。Propel提供了基于现有数据库模式生成类结构的选项。它为每个表创建两个对象。第一个对象是一个很长的访问函数列表,类似于您当前列出的;findByAttribute (attribute_value美元)。下一个对象继承自第一个对象。您可以更新此子对象以构建更复杂的getter函数。

另一个解决方案是使用__call()将未定义的函数映射到可操作的函数。你的__call方法将能够将findById和findByName解析为不同的查询。

public function __call($function, $arguments) {
    if (strpos($function, 'findBy') === 0) {
        $parameter = substr($function, 6, strlen($function));
        // SELECT * FROM $this->table_name WHERE $parameter = $arguments[0]
    }
}

我希望这能有所帮助。

我将在此补充一点,因为我目前正试图掌握所有这些内容。

#1和2

这是一个完美的地方,您的ORM做繁重的工作。如果你正在使用一个实现了某种ORM的模型,你可以使用它的方法来处理这些事情。如果需要,可以创建自己的orderBy函数来实现Eloquent方法。举个例子:

class DbUserRepository implements UserRepositoryInterface
{
    public function findAll()
    {
        return User::all();
    }

    public function get(Array $columns)
    {
       return User::select($columns);
    }

你要找的似乎是ORM。没有理由你的存储库不能基于一个。这将需要用户扩展雄辩,但我个人不认为这是一个问题。

然而,如果您确实想避免ORM,那么您将不得不“自己滚动”以获得您想要的东西。

#3

接口不应该是硬性要求。可以实现接口并向其添加内容。它不能做的是未能实现该接口所需的功能。你也可以像类一样扩展接口来保持DRY。

也就是说,我才刚刚开始理解,但这些认识对我很有帮助。

我建议https://packagist.org/packages/prettus/l5-repository作为供应商来实现存储库/标准等…在Laravel5:D

Issue #3: Impossible to match an interface I see the benefit in using interfaces for repositories, so I can swap out my implementation (for testing purposes or other). My understanding of interfaces is that they define a contract that an implementation must follow. This is great until you start adding additional methods to your repositories like findAllInCountry(). Now I need to update my interface to also have this method, otherwise, other implementations may not have it, and that could break my application. By this feels insane...a case of the tail wagging the dog.

我的直觉告诉我,这可能需要一个实现查询优化方法和泛型方法的接口。对性能敏感的查询应该有针对性的方法,而不频繁或轻量级的查询则由通用处理程序处理,这可能会使控制器做更多的杂耍。

泛型方法将允许实现任何查询,因此将防止在过渡期间发生破坏性更改。目标方法允许您在有意义时优化调用,并且它可以应用于多个服务提供者。

这种方法类似于硬件实现执行特定的优化任务,而软件实现只做简单的工作或灵活的实现。