多年来,我一直在一遍又一遍地重新实现相同的代码(随着进化),但没有找到某种干净、有效的方法来将其抽象出来。
该模式是我的服务层中的基本“find[Type]s”方法,它将选择查询创建抽象为服务中的单个点,但支持快速创建更易于使用的代理方法的能力(请参阅示例 PostServivce::getPostById () 方法如下)。
不幸的是,到目前为止,我还无法实现这些目标:
- 减少因不同的重新实现而引入错误的可能性
- 向 IDE 公开有效/无效参数选项以进行自动补全
- 遵循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
这个基本函数的好处是:
- 它使我能够随着模式的发展快速支持新的条件和选项
- 它使我能够快速实现查询的全局条件(例如,添加默认值为 true 的“excludeDisabled”选项,并过滤所有禁用 = 0 模型,除非调用者明确表示不同)。
- 它允许我快速创建新的、更易于使用的方法,这些方法代理回调到 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 ... */
}
The MAJOR这种方法的缺点是:
- 在每个模型访问服务中都会创建相同的整体“find[Model]s”方法,大多数情况下仅条件切换构造和基表名称发生变化。
- 没有简单的方法来执行 AND/OR 条件运算。所有条件都明确进行 AND 运算。
- 引入了很多拼写错误的机会
- 引入了许多打破基于约定的 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 时创建 Foo\Options\FindConditions\Comparison 类环绕值的泥沼价值 ($conditions->setCondition('Foo', new Comparison('NOT LIKE', 'bar'));
).
如果存在的话,我宁愿使用其他人的解决方案,但我还没有遇到任何可以满足我需求的解决方案。
我想超越这个过程,回到实际构建我正在从事的项目,但我什至看不到结束的迹象。
所以,堆栈溢出者:
- 有没有更好的方法可以提供我所确定的优点而不包括缺点?