多年来,我一直在一遍又一遍地(随着进化)重新实现相同的代码,却没有找到一些干净、有效地将其抽象出来的方法。
该模式是我的服务层中的基本“find[Type]s”方法,它将选择查询创建抽象到服务中的单个点,但支持快速创建更易于使用的代理方法的能力(参见示例 PostServivce::getPostById () 方法方法如下)。
不幸的是,到目前为止,我一直无法满足这些目标:
我最近的实现通常类似于以下示例。该方法接受一组条件和一组选项,并从中创建并执行一个 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 ... */
}
噗
这个基函数的好处是:
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 ... */
}
专业 这种方法的缺点是:
在过去的几天里,我试图为这个问题开发一个更面向对象的解决方案,但我觉得我正在开发一个太复杂的解决方案,这个解决方案过于僵化和限制使用。
我正在努力的想法类似于以下内容(当前项目将是 Doctrine2 fyi,因此略有变化)...
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 提供一个迭代器接口(interface)来循环选项。
不幸的是,经过几天的黑客攻击后,我对这个系统的复杂性感到沮丧。照原样,仍然不支持条件组和 OR 条件,并且在指定 FindConditions 时创建 Foo\Options\FindConditions\Comparison 类环绕一个值的能力指定备用条件比较运算符已经是一个完整的泥潭值 (
$conditions->setCondition('Foo', new Comparison('NOT LIKE', 'bar'));
)。如果存在,我更愿意使用其他人的解决方案,但我还没有遇到任何可以满足我的需求的解决方案。
我想超越这个过程并回到实际构建我正在处理的项目中,但我什至看不到尽头。
所以,堆栈溢出者:
- 有没有更好的方法可以提供我已经确定的好处而不包括缺点?
最佳答案
我认为你把事情复杂化了。
我使用 Doctrine 2 开发了一个项目,它有很多实体,它们的不同用途,各种服务,自定义存储库等,我发现这样的东西效果很好(无论如何对我来说)。
1. 用于查询的存储库
首先,我通常不会在服务中进行查询。 Doctrine 2 提供了 EntityRepository 以及为此确切目的为每个实体对其进行子类化的选项。
UserRepository.findByNameStartsWith
之类的东西以及诸如此类的事情。 所以换句话说...
2. 结合非实体逻辑的服务
使用服务将“事务”组合在一个简单的界面后面,您可以从 Controller 使用或通过单元测试轻松测试。
例如,假设您的用户可以添加 friend 。每当用户与其他人成为 friend 时,就会向其他人发送一封电子邮件以进行通知。这是您在服务中会拥有的东西。
您的服务将(例如)包含一个方法
addNewFriend
这需要两个用户。然后,它可以使用存储库来查询一些数据,更新用户的 friend 数组,并调用一些其他类然后发送电子邮件。您可以在服务中使用 entitymanager 来获取存储库类或持久化实体。
3. 实体特定逻辑的实体
最后,您应该尝试将特定于实体的业务逻辑直接放入实体类中。
这种情况的一个简单示例可能是,在上述场景中发送的电子邮件可能使用某种问候语......“你好安德森先生”或“你好安德森女士”。
例如,您需要一些逻辑来确定适当的问候语。这是您可以在实体类中拥有的东西 - 例如,
getGreeting
或其他东西,然后可以考虑用户的性别和国籍,并基于此返回一些内容。 (假设性别和国籍将存储在数据库中,而不是问候语本身 - 问候语将由函数的逻辑计算)我可能还应该指出,实体通常不应该知道实体管理器或存储库。如果逻辑需要其中任何一个,它可能不属于实体类本身。
这种方法的好处
我发现我在这里详述的方法效果很好。它是可维护的,因为它通常对事物的作用非常“明显”,它不依赖于复杂的查询行为,并且由于事物被清楚地划分为不同的“区域”(存储库、服务、实体),因此单元测试非常简单好。
关于php - 帮助使用 DRY 原则在服务类中创建灵活的基础 'find' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629432/