Bre*_*t C 5 php zend-framework query-builder service-layer doctrine-orm
多年来,我一直在重复实现相同的代码(使用进化)而没有找到一些干净,有效,抽象出来的方法.
该模式是我的服务层中的基本'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 ... */
}
Run Code Online (Sandbox Code Playgroud)
Phewf
这个基本功能的好处是:
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 ... */
}
Run Code Online (Sandbox Code Playgroud)
这种方法的主要缺点是:
在过去的几天里,我试图为这个问题开发一个更多的OO解决方案,但感觉我正在开发太复杂的解决方案,这个解决方案过于严格和限制使用.
我正在努力的想法是下面的内容(当前的项目将是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 ... */
}
Run Code Online (Sandbox Code Playgroud)
最后,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 */
}
Run Code Online (Sandbox Code Playgroud)
Foo\Options\FindConditions和Foo\Options\FindOptions非常相似,所以,至少现在它们都扩展了一个普通的Foo\Options父类.此父类处理初始化允许的变量和默认值,访问set选项,限制只访问已定义的选项,以及为DqlOptionsMapper提供迭代器接口以循环选项.
不幸的是,经过几天的黑客攻击后,我对这个系统的复杂性感到沮丧.对于条件组和OR条件,仍然没有这方面的支持,并且指定备用条件比较运算符的能力一直是在指定FindConditions时创建Foo\Options\FindConditions\Comparison类环绕值的完全困境value($conditions->setCondition('Foo', new Comparison('NOT LIKE', 'bar'));).
我宁愿使用其他人的解决方案,如果它存在,但我还没有遇到任何我正在寻找的东西.
我想超越这个过程,回到实际构建我正在进行的项目,但我甚至看不到目标.
那么,Stack Overflowers: - 有没有更好的方法可以提供我已经确定的好处而不包括缺点?
我认为你把事情过于复杂化了。
我曾经使用 Doctrine 2 开发过一个项目,该项目有相当多的实体、它们的不同用途、各种服务、自定义存储库等,并且我发现类似的东西效果相当好(无论如何对我来说)。
首先,我一般不会在服务中进行查询。Doctrine 2 提供了 EntityRepository 以及为此目的为每个实体对其进行子类化的选项。
UserRepository.findByNameStartsWith。所以换句话说...
使用服务将“事务”组合到一个简单的界面后面,您可以从控制器使用或通过单元测试轻松进行测试。
例如,假设您的用户可以添加朋友。每当用户与其他人成为好友时,就会向对方发送一封电子邮件以进行通知。这是您在服务中应该拥有的东西。
例如,您的服务将包括addNewFriend需要两个用户的方法。然后,它可以使用存储库来查询一些数据,更新用户的朋友数组,并调用其他一些类来发送电子邮件。
您可以在服务中使用实体管理器来获取存储库类或持久实体。
最后,您应该尝试将特定于实体的业务逻辑直接放入实体类中。
这种情况的一个简单例子是,在上述场景中发送的电子邮件可能使用某种问候语......“你好安德森先生”或“你好安德森女士”。
例如,您需要一些逻辑来确定适当的问候语。这是您可以在实体类中拥有的东西 - 例如,getGreeting或者其他东西,然后可以考虑用户的性别和国籍并基于此返回一些东西。(假设性别和国籍将存储在数据库中,但问候语本身不会存储 - 问候语将由函数的逻辑计算)
我可能还应该指出,实体通常不应该知道实体管理器或存储库。如果逻辑需要其中任何一个,它可能不属于实体类本身。
我发现我在这里详细介绍的方法效果相当好。它是可维护的,因为它通常对事物的作用非常“明显”,它不依赖于复杂的查询行为,并且因为事物被清楚地划分为不同的“区域”(存储库、服务、实体),所以单元测试非常简单出色地。
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |