帮助创建灵活的底座'find'方法中使用DRY原则


Help creating a flexible base 'find' method in a service class using the DRY principle

多年来,我一直在一遍又一遍地重新实现相同的代码(随着进化),却没有找到一些干净、有效的方法来抽象它。

模式是我的服务层中的一个基本的'find[Type]s'方法,它将选择查询创建抽象到服务中的单个点,但支持快速创建更容易使用的代理方法的能力(参见下面的示例postservice::getPostById()方法)。

不幸的是,到目前为止,我还不能满足这些目标:

  1. 减少由不同的重新实现引入的错误的可能性
  2. 向ide显示有效/无效的参数选项以实现自动完成
  3. 遵循DRY原则

我最近的实现通常看起来像下面的例子。该方法接受一个条件数组和一个选项数组,并从中创建和执行一个Doctrine_Query(我今天在这里重写了大部分内容,因此可能存在一些拼写错误/语法错误,这不是直接剪切和粘贴)。

class PostService
{
    /* ... */
    /**
     * Return a set of Posts
     *
     * @param Array $conditions Optional. An array of conditions in the format
     *                          array('condition1' => 'value', ...)
     * @param Array $options    Optional. An array of options 
     * @return Array An array of post objects or false if no matches for conditions
     */
    public function getPosts($conditions = array(), $options = array()) {
        $defaultOptions =  = array(
            'orderBy' => array('date_created' => 'DESC'),
            'paginate' => true,
            'hydrate' => 'array',
            'includeAuthor' => false,
            'includeCategories' => false,
        );
        $q = Doctrine_Query::create()
                        ->select('p.*')
                        ->from('Posts p');
        foreach($conditions as $condition => $value) {
            $not = false;
            $in = is_array($value);
            $null = is_null($value);                
            $operator = '=';
            // This part is particularly nasty :(
            // allow for conditions operator specification like
            //   'slug LIKE' => 'foo%',
            //   'comment_count >=' => 1,
            //   'approved NOT' => null,
            //   'id NOT IN' => array(...),
            if(false !== ($spacePos = strpos($conditions, ' '))) {
                $operator = substr($condition, $spacePost+1);
                $conditionStr = substr($condition, 0, $spacePos);
                /* ... snip validate matched condition, throw exception ... */
                if(substr($operatorStr, 0, 4) == 'NOT ') {
                  $not = true;
                  $operatorStr = substr($operatorStr, 4);
                }
                if($operatorStr == 'IN') {
                    $in = true;
                } elseif($operatorStr == 'NOT') {
                    $not = true;
                } else {
                    /* ... snip validate matched condition, throw exception ... */
                    $operator = $operatorStr;
                }
            }
            switch($condition) {
                // Joined table conditions
                case 'Author.role':
                case 'Author.id':
                    // hard set the inclusion of the author table
                    $options['includeAuthor'] = true;
                    // break; intentionally omitted
                /* ... snip other similar cases with omitted breaks ... */
                    // allow the condition to fall through to logic below
                // Model specific condition fields
                case 'id': 
                case 'title':
                case 'body':
                /* ... snip various valid conditions ... */
                    if($in) {
                        if($not) {
                            $q->andWhereNotIn("p.{$condition}", $value);
                        } else {
                            $q->andWhereIn("p.{$condition}", $value);
                        }
                    } elseif ($null) {
                        $q->andWhere("p.{$condition} IS " 
                                     . ($not ? 'NOT ' : '') 
                                     . " NULL");
                    } else {
                        $q->andWhere(
                            "p.{condition} {$operator} ?" 
                                . ($operator == 'BETWEEN' ? ' AND ?' : ''),
                            $value
                        );
                    }
                    break;
                default:
                    throw new Exception("Unknown condition '$condition'");
            }
        }
        // Process options
        // init some later processing flags
        $includeAuthor = $includeCategories = $paginate = false;
        foreach(array_merge_recursivce($detaultOptions, $options) as $option => $value) {
            switch($option) {
                case 'includeAuthor':
                case 'includeCategories':
                case 'paginate':
                /* ... snip ... */
                    $$option = (bool)$value;
                    break;
                case 'limit':
                case 'offset':
                case 'orderBy':
                    $q->$option($value);
                    break;
                case 'hydrate':
                    /* ... set a doctrine hydration mode into $hydration */ 
                    break;
                default:
                    throw new Exception("Invalid option '$option'");
            }
        }
        // Manage some flags...
        if($includeAuthor) {
            $q->leftJoin('p.Authors a')
              ->addSelect('a.*');
        } 
        if($paginate) {
            /* ... wrap query in some custom Doctrine Zend_Paginator class ... */
            return $paginator;
        }
        return $q->execute(array(), $hydration);
    }
    /* ... snip ... */
}

Phewf

这个基本函数的好处是:

  1. 它允许我在模式演变时快速支持新的条件和选项
  2. 它允许我在查询上快速实现全局条件的方法(例如,添加一个默认为true的'excludeDisabled'选项,并过滤所有disabled = 0模型,除非调用者明确表示不同)。
  3. 它允许我快速创建新的,更容易使用的方法,代理调用回findPosts方法。例如:
class PostService
{
    /* ... snip ... */
    // A proxy to getPosts that limits results to 1 and returns just that element
    public function getPost($conditions = array(), $options()) {
        $conditions['id'] = $id;
        $options['limit'] = 1;
        $options['paginate'] = false;
        $results = $this->getPosts($conditions, $options);
        if(!empty($results) AND is_array($results)) {
            return array_shift($results);
        }
        return false;
    }
    /* ... docblock ...*/       
    public function getPostById(int $id, $conditions = array(), $options()) {
        $conditions['id'] = $id;
        return $this->getPost($conditions, $options);
    }
    /* ... docblock ...*/
    public function getPostsByAuthorId(int $id, $conditions = array(), $options()) {
        $conditions['Author.id'] = $id;
        return $this->getPosts($conditions, $options);
    }
    /* ... snip ... */
}
这种方法的主要缺点是:
  • 在每个模型访问服务中都创建了相同的单一'find[Model]s'方法,大多数情况下只有条件开关结构和基表名称发生了变化。
  • 没有简单的方法来执行AND/OR条件操作。
  • 引入了许多出现打字错误的机会
  • 在基于约定的API中引入了许多中断的机会(例如,以后的服务可能需要实现不同的语法约定来指定orderBy选项,这对于向后移植到所有以前的服务来说变得非常繁琐)。
  • 违反DRY原则。
  • 有效的条件和选项隐藏在IDE自动完成解析器中,并且选项和条件参数需要冗长的文档块解释才能跟踪允许的选项。

在过去的几天里,我试图开发一个更面向对象的解决方案来解决这个问题,但我觉得我正在开发一个过于复杂的解决方案,它将过于僵化和限制使用。

我的想法是沿着下面的路线(当前的项目将是Doctrine2,所以有轻微的变化)…

namespace Foo'Service;
use Foo'Service'PostService'FindConditions; // extends a common 'Foo'FindConditions abstract
use Foo'FindConditions'Mapper'Dql as DqlConditionsMapper;
use Foo'Service'PostService'FindOptions; // extends a common 'Foo'FindOptions abstract
use Foo'FindOptions'Mapper'Dql as DqlOptionsMapper;
use 'Doctrine'ORM'QueryBuilder;
class PostService
{
    /* ... snip ... */
    public function findUsers(FindConditions $conditions = null, FindOptions $options = null) {
        /* ... snip instantiate $q as a Doctrine'ORM'QueryBuilder ... */
        // Verbose
        $mapper = new DqlConditionsMapper();
        $q = $mapper
                ->setQuery($q)
                ->setConditions($conditions)
                ->map();
        // Concise
        $optionsMapper = new DqlOptionsMapper($q);        
        $q = $optionsMapper->map($options);

        if($conditionsMapper->hasUnmappedConditions()) {
            /* .. very specific condition handling ... */
        }
        if($optionsMapper->hasUnmappedConditions()) {
            /* .. very specific condition handling ... */
        }
        if($conditions->paginate) {
            return new Some_Doctrine2_Zend_Paginator_Adapter($q);
        } else {
            return $q->execute();
        }
    }
    /* ... snip ... */
}

最后,Foo'Service'PostService'FindConditions类的示例:

namespace Foo'Service'PostService;
use Foo'Options'FindConditions as FindConditionsAbstract;
class FindConditions extends FindConditionsAbstract {
    protected $_allowedOptions = array(
        'user_id',
        'status',
        'Credentials.credential',
    );
    /* ... snip explicit get/sets for allowed options to provide ide autocompletion help */
}

Foo'Options'FindConditions和Foo'Options'FindOptions实际上非常相似,因此,至少现在,它们都扩展了一个常见的Foo'Options父类。这个父类处理初始化允许的变量和默认值,访问已设置的选项,限制对仅定义的选项的访问,并为DqlOptionsMapper提供一个迭代器接口来循环遍历选项。

不幸的是,在破解这个系统几天之后,我对这个系统的复杂性感到沮丧。实际上,它仍然不支持条件组和OR条件,并且在指定FindConditions值($conditions->setCondition('Foo', new Comparison('NOT LIKE', 'bar'));)时,创建Foo'Options'FindConditions' comparison类包装值的能力一直是一个完全的泥潭。

如果存在的话,我更愿意使用别人的解决方案,但是我还没有遇到任何我正在寻找的解决方案。

我想跳过这个过程,回到我正在做的项目中去,但我甚至看不到结束的迹象。

那么,Stack Overflowers:是否有更好的方法可以提供我所确定的好处而不包括缺点?

我觉得你把事情弄得太复杂了。

我曾在一个项目中使用Doctrine 2,它有相当多的实体,不同的用途,各种服务,自定义存储库等,我发现这样的工作相当不错(对我来说).

1。查询存储库

首先,我一般不会在服务中进行查询。原则2提供了EntityRepository,并为每个实体子类化它。

  • 只要有可能,我使用标准的findOneBy…将其作为findBy和…样式魔术方法。这使我不必自己编写DQL,并且开箱即用。
  • 如果我需要更复杂的查询逻辑,我通常在存储库中创建特定于用例的查找器。这些是像UserRepository.findByNameStartsWith之类的东西我一般不会创建一个超级花哨的"我可以接受你给我的任何参数!"类型的魔法查找器。如果我需要一个特定的查询,我添加一个特定的方法。虽然这似乎需要您编写更多代码,但我认为这是一种更简单、更容易理解的做事方式。(我试着通过你的查找器代码,它是相当复杂的地方寻找)

也就是说

  • 尝试使用已经给你的学说(魔法查找器方法)
  • 如果需要自定义查询逻辑,请使用自定义存储库类
  • 为每个查询类型创建一个方法

2。用于组合非实体逻辑的服务

使用服务将"事务"组合在一个简单的接口后面,您可以从控制器中使用或轻松地通过单元测试进行测试。

例如,假设您的用户可以添加好友。当一个用户与另一个人成为好友时,就会向另一个人发送一封通知邮件。这是你应该在你的服务。

你的服务将(例如)包含一个方法addNewFriend,它接受两个用户。然后,它可以使用存储库来查询一些数据,更新用户的好友数组,并调用其他一些类,然后发送电子邮件。

你可以在你的服务中使用entitymanager来获取存储库类或持久化实体。

3。用于实体特定逻辑的实体

最后,您应该尝试将特定于实体的业务逻辑直接放入实体类中。

这种情况的一个简单的例子可能是,在上述场景中发送的电子邮件可能使用某种形式的问候语。"你好,安德森先生"或"你好,安德森女士"。

例如,您需要一些逻辑来确定适当的问候语。这是您可以在实体类中拥有的东西-例如,getGreeting或其他东西,它可以考虑用户的性别和国籍并基于此返回一些东西。(假设性别和国籍将存储在数据库中,而不是问候语本身—问候语将由函数的逻辑计算) 我可能还应该指出实体通常应该不应该知道实体管理器或存储库。如果逻辑需要其中任何一个,它可能不属于实体类本身。

这种方法的优点

我发现我在这里详细介绍的方法工作得相当好。它是可维护的,因为它通常是非常"明显"的东西做什么,它不依赖于复杂的查询行为,而且因为东西被清楚地划分为不同的"区域"(repos,服务,实体),所以单元测试也非常简单。