背景
最近有需求实现类似于 QueryBuilder 的谓词语句,就去翻看了它的源码。先看两个例子
例子1
$qb = $em->createQueryBuilder();
$qb->select('*')->from('User','u')->where('u.id = 1');
echo $qb->getDQL();
例子2
$qb = $em->createQueryBuilder();
$qb->select('*')
->from('User','u')
->where('u.id = 1')
->andWhere('u.score >= 90')
->orWhere('u.score <= 100');
echo $qb->getDQL();
是不是有点懵逼,希望看完我的文章,希望你有所收获。
接下来会以例子2讲解,分别解释 where、andWhere、orWhere 方法,图文并茂,一步步教你理解上述PHP代码转换为sql语句的原理。
代码不难,建议大家配合源码食用。[相关源码在此]https://github.com/doctrine/orm/blob/master/lib/Doctrine/ORM/QueryBuilder.php(https://github.com/doctrine/orm/blob/master/lib/Doctrine/ORM/QueryBuilder.php
)
添加谓词语句
先看 QueryBuilder::where 方法,生成了一个Andx 谓词对象 $predicates ,
public function where($predicates)
{
if ( ! (func_num_args() == 1 && $predicates instanceof ExprComposite)) {
$predicates = new ExprAndx(func_get_args());
}
return $this->add('where',$predicates);
}
执行 var_export($predicates) 后查看成员变量如下,separator 是 where 子句条件之间的连接符,有 AND 和 OR。parts 是由条件组成的数组。
// var_export($predicates)的输出
DoctrineORMQueryExprAndx::__set_state(array(
'separator' => ' AND ','allowedClasses' =>
array (
0 => 'DoctrineORMQueryExprComparison',1 => 'DoctrineORMQueryExprFunc',2 => 'DoctrineORMQueryExprOrx',3 => 'DoctrineORMQueryExprAndx',),'preSeparator' => '(','postSeparator' => ')','parts' =>
array (
0 => 'u.id = 1',))
接下来执行的return $this->add('where',$predicates); 函数很简单,把谓词对象作为QueryBuilder::_dqlParts 中的key为where的value,打印QueryBuilder对象如下
// 此函数有删减,完整请看官方源码
// QueryBuilder的add方法
public function add($dqlPartName,$dqlPart,$append = false)
{
$isMultiple = is_array($this->_dqlParts[$dqlPartName])
&& !($dqlPartName == 'join' && !$append);
// $isMultiple 这里的值为 false
$this->_dqlParts[$dqlPartName] = ($isMultiple) ? [$dqlPart] : $dqlPart;
$this->_state = self::STATE_DIRTY;
return $this;
}
// _dqlParts 结构
array (
...
'where' =>
DoctrineORMQueryExprAndx::__set_state(array(
'separator' => ' AND ',))
...
接下来具体看 QueryBuilder::andWhere 方法,
getDQLPart取出的是刚才设置的Andx对象,接着执行Andx的addMultiple方法,最终调用的是Andx::add方法,这个方法最终是把'u.score >= 90'加入到Andx::parts数组中
// QueryBuilder
public function andWhere()
{
$args = func_get_args();
$where = $this->getDQLPart('where');
if ($where instanceof ExprAndx) {
$where->addMultiple($args);
} else {
array_unshift($args,$where);
$where = new ExprAndx($args);
}
return $this->add('where',$where);
}
// Andx
public function add($arg)
{
if ( $arg !== null && (!$arg instanceof self || $arg->count() > 0) ) {
// If we decide to keep ExprBase instances,we can use this check
if ( ! is_string($arg)) {
$class = get_class($arg);
if ( ! in_array($class,$this->allowedClasses)) {
throw new InvalidArgumentException("Expression of type '$class' not allowed in this context.");
}
}
$this->parts[] = $arg;
}
return $this;
}
所以此时Andx::parts数组中有了两个元素:'u.id = 1' 和 'u.score >= 90'
DoctrineORMQueryExprAndx::__set_state(array(
'separator' => ' AND ',1 => 'u.score >= 90',))
继续看QueryBuilder::orWhere 方法,取出的 $where 是刚刚andWhere 执行后设置的 Andx 对象,执行 array_unshift($args,$where) 语句后,形成的 $args 由一个 Andx 对象和一个字符串 'u.score <= 100' 组成。
public function orWhere()
{
$args = func_get_args();
$where = $this->getDQLPart('where');
if ($where instanceof ExprOrx) {
$where->addMultiple($args);
} else {
array_unshift($args,$where);
$where = new ExprOrx($args);
}
return $this->add('where',$where);
}
将包含 Andx 对象和字符串 u.score <= 100 的 $args 数组作为 Orx 对象的构造方法,Orx 构造函数的内部实现是 addMultiple 方法,最终调用 Orx::add 方法将 $args 中的元素全部都加到 Orx对象 的 $parts 对象中,最终 Orx 对象的 parts 内容的示意图的阶段 3 所示

我整理了一下添加逻辑如下所示

解析谓词语句
谓词对象转换成谓词语句其实就是一句话,
$queryPart = $this->getDQLPart($queryPartName);
echo $queryPart;
不要觉得奇怪,对象也可以当作字符串用,引用PHP手册上的原话
__toString() 方法用于一个类被当成字符串时应怎样回应。
谓词对象的__toString 的实现在DoctrineORMQueryExprComposite ,一起来看看
public function __toString()
{
if ($this->count() === 1) {
return (string) $this->parts[0];
}
$components = [];
foreach ($this->parts as $part) {
$components[] = $this->processQueryPart($part);
}
return implode($this->separator,$components);
}
private function processQueryPart($part)
{
$queryPart = (string) $part;
if (is_object($part) && $part instanceof self && $part->count() > 1) {
return $this->preSeparator . $queryPart . $this->postSeparator;
}
if (stripos($queryPart,' OR ') !== false || stripos($queryPart,' AND ') !== false) {
return $this->preSeparator . $queryPart . $this->postSeparator;
}
return $queryPart;
}
带入之前组合好的 Orx 对象,一起来分析下。Orx 对象parts属性的两个元素分别会被带入processQueryPart执行。
Andx 你先来,走到$queryPart = (string) $part ,我们希望$part 被当作字符串处理,继续回到__toString ,这里是个递归。
Andx对象parts属性的两个字符串元素继续带入processQueryPart执行。这两个字符串经过处理会作为Andx对象的$components 的元素,最终经过implode($this->separator,$components) 返回字符串 u.id=1 and u.score >= 90 ,此时的值会被返回到 $queryPart 。
接下来执行到的是 return $this->preSeparator . $queryPart . $this->postSeparator; 到 Orx 对象的 $components 的数组中去。
// $part 是 Andx 对象
// Andx 对象 经过字符串化后成了 u.id=1 and u.score >= 90,赋值给 $queryPart
$queryPart = (string) $part;
// 因为Andx对象有两个条件,所以左右两边会被加上括号,最终返回 (u.id = 1 AND u.score >= 90)
if (is_object($part) && $part instanceof self && $part->count() > 1) {
return $this->preSeparator . $queryPart . $this->postSeparator;
}
Orx 对象parts属性的第一个元素已经处理完毕,接下来是第二个元素u.score <= 100 ,字符串就很简单了,直接返回到 Orx 对象的 $components 中去!
现在来看看Orx 对象的 $components 中间有啥了
array (
0 => '(u.id = 1 AND u.score >= 90)',1 => 'u.score <= 100',)
再用implode切割成字符串 结果就是出来了(u.id = 1 AND u.score >= 90) OR u.score <= 100 ,解析完毕!看不懂的同学看我整理的流程图。

总结
具体细节大家可以使用 phpStorm + xdebug 单步调试研究。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|