ITeye博客

实现php超级查询(应该能满足大部分查询需求)

wolferill · 2010-07-30 10:28 · php学习 · 编程语言 · Markdown

本来是搞Java的,可由于项目需求,无奈暂时转战PHP,刚学一个星期,不过用起来也还勉强顺手。

 

没有了Hibernate这样强大的中间件框架的支持,php要访问数据库我只能从基本的sql语句写起了(不知道php高手们是怎么做的,有好工具就推荐一下吧,在下感激不尽)。

 

不同的表有不同的查询语句,又between又in还要order by,真是崩溃呀,为了实现那些各式各样的sql查询语句,秉着“不重复发明轮子的精神”,我设计了一个“准工厂模式”的php函数,可以根据需求生成sql查询语句,应当能满足大部分的需求了。

 

使用方法如下:

 

<?php

//使用范例:
include("searchBean.php");
$conditions = array(new SearchBean("type_id", "in", array(31, 42, 44)),
	new SearchBean("title", "like", "php超级查询"),
	new SearchBean("hit", ">", 20),
	new SearchBean("id", "order by", 0),
	new SearchBean("content", "is not null"),
	new SearchBean("add_time", "between", array('2009-07-29', '2010-07-29')));
echo create_sql ("news", $conditions, 0, 10)."<br>";

?>

 

输出如下:

 

select * from news 
where type_id in (31, 42, 44) and 
        title like '%php超级查询%' and 
        hit > 20 and 
        content is not null 
        and add_time between '2009-07-29' and '2010-07-29' 
order by id ASC 
Limit 0,10

 

searchBean.php文件中的主要代码如下(有提供下载哟!):

 

<?php

/**
 * 用于封装数据库查询条件的类
 * @author Technicolor
 */
class SearchBean {

	private $column;
	private $relation;
	private $value;

	/**
	 * 构造函数
	 * @param string $column 查询的列名
	 * @param string $relation 查询关系,必须为小写字母,支持如下条件:<br>
	 *  =,>,>=,<,<=,<>,like,between,in,is null,order by(以及对应的not关系)
	 * @param string $value 查询的值,当$relation为like时,字符串自动首尾添加"%";<br>
	 * 当$relation为between时,$value应当为数组参数,取数组的前两个值作为between的范围,且$value[0]较小<br>
	 * 当$relation为in时,$value应当为数组参数<br>
	 * 当$relation为is null时,$value参数将被忽略<br>
	 * 当$relation为order by时,value为1则降序,0则升序
	 */
	function SearchBean($column, $relation, $value=null) {//略  }

	function get_column() {//略	}

	function get_relation() {//略	}

	function get_value() {//略	}

	/**
	 * 将array转换为对应的sql in片断
	 * @param array $array SQL IN 参数数组
	 * @return string SQL IN:<br>
	 * (1,2,3,…)或('a','b','c')
	 */
	private static function trans_value_in($array) {//略	}

	/**
	 * 将array转换为对应的sql between片断
	 * @param array $array SQL BETWEEN 参数数组
	 * @return string SQL BETWEEN:<br>
	 * 1 and 2 或 'a' and 'b'
	 */
	private static function trans_value_between($array) {//略  }

	/**
	 * 将SearchBean转换为对应的sql查询条件片断
	 * @return string sql查询条件片断
	 */
	function to_sql() {
		$sql = "";
		if (is_null($this->value) &&
				$this->relation != "is null" &&
				$this->relation != "is not null") {
			return $sql;
		}
		if ($this->relation == "order by") {
			$type = $this->value ? "DESC" : "ASC";
			$sql = "$this->column $type";
		} else if ($this->relation == "in" || $this->relation == "not in") {
			$sql = "$this->column $this->relation " . self::trans_value_in($this->value);
		} else if ($this->relation == "between" || $this->relation == "not between") {
			$sql = "$this->column $this->relation " . self::trans_value_between($this->value);
		} else if ($this->relation == "like" || $this->relation == "not like") {
			$sql = "$this->column $this->relation '%$this->value%'";
		} else if ($this->relation == "is null" || $this->relation == "is not null") {
			$sql = "$this->column $this->relation";
		} else {
			if (is_string($this->value)) {
				$sql = "$this->column $this->relation '$this->value'";
			} else {
				$sql = "$this->column $this->relation $this->value";
			}
		}
		return $sql;
	}

}


/**
 * 生成sql查询语句
 * @param string $tableName 查询的表名
 * @param array(SearchBean) $conditions 查询条件列表
 * @param int $start 查询起始索引(用于分页)
 * @param int $limit 查询限制个数(每页显示个数)
 * @param int $count 0则为“select *”,1则为“select count(*)”(用于统计个数)
 */
function create_sql($tableName, $conditions="", $start=0, $limit=0, $count=0) {
	$page = "";
	if ($start >= 0 && $limit > 0) {
		$page = " Limit " . $start . "," . $limit;
	}
	$where = 0;
	$where_sql = "";
	$order_by = 0;
	$order_by_sql = "";
	if (is_a($conditions, "SearchBean")) {
		$relation = $conditions->get_relation();
		if ($relation == "order by") {
			$order_by_sql = $conditions->to_sql();
			$order_by++;
		} else {
			$where_sql = $conditions->to_sql();
			$where++;
		}
	} else if (is_array($conditions)) {
		foreach ($conditions as $c) {
			if (is_a($c, "SearchBean")) {
				$str = $c->to_sql();
				if ($str) {
					$relation = $c->get_relation();
					if ($relation == "order by") {
						$order_by_sql = $order_by ? $order_by_sql . ", " . $str : $str;
						$order_by++;
					} else {
						$where_sql = $where ? $where_sql . " and " . $str : $str;
						$where++;
					}
				}
			}
		}
	}
	$where_sql = $where ? " where " . $where_sql : "";
	$order_by_sql = $order_by ? " order by " . $order_by_sql : "";
	$sql = "";
	if ($count) {
		$sql = "select count(*) from $tableName" . $where_sql;
	} else {
		$sql = "select * from $tableName" . $where_sql . $order_by_sql . $page;
	}
	return $sql;
}
?>

 

当然,上面那部分只生成了sql语句,还没有进行查询,对查询那部分我是这样做的:

1、将所有数据库中常用的表设计成类,库表列对应于类的成员变量;

2、在系统中记录数据库表名称和类名称的双向映射;

3、提供一个通用查询函数,返回值是该表对应的类的对象的数组,函数中通过表名判断需要生成的对象类型。

 

具体实现就不放出来了,与具体项目相关,可根据需要对searchBean.php中的函数进行封装

评论(7)

  1. #7 楼 · vb2005xu · 2010-08-11 10:02

    6楼思维还是停留在PHP4,根本不懂PHP5

  2. #6 楼 · bobboy007 · 2010-08-06 17:32

    php这样搞没多少意义,容易陷入过度设计。性能损失很厉害。 到php5对面向对象支持都一般般, 要真用到这么多架构还是选java.当然现在很多php框架开发的不错。但php本质还是面向过程多。

  3. #5 楼 · vb2005xu · 2010-08-02 10:27

    建议 看下 QEE 然后再来评价 PHP ORM ....

  4. #4 楼 · zhouzhao21 · 2010-07-31 12:21

    symfony 不错。 我也做了几年 java 了, 没有什么好不好的。合适就行。

  5. #3 楼 · kk15378924 · 2010-07-30 16:19

    效率.... php干orm是很吃力不讨好的...

  6. #2 楼 · wolferill · 2010-07-30 13:00

    vb2005xu writes:

    看看呵呵 , [code=php]

    /**

    • 返回复合条件字符串,解决ZF组合条件不能自动生成的问题

    …… …… …… [/code]

    呵呵,谢谢了

    刚刚看了些PHP的MVC框架,感觉还是蛮强大的

  7. #1 楼 · vb2005xu · 2010-07-30 10:56

    看看呵呵 ,

    
    
    	/**
    	 * 返回复合条件字符串,解决ZF组合条件不能自动生成的问题
    	 * 
    	 * 	用法:
    	 *	$sql_cond = Zend_Custom_DB_TableDataGateway::getConditions(
    	 *		Zend_Custom_DB_TableDataGateway::getDefaultAdapter() ,
    	 *		array(
    	 *			'first_name' => 'iamsese' ,
    	 *			'age' => array(18,'>=') ,
    	 *			'grade' => array(72,'>','OR') ,
    	 *			'last_name' => array('%kenxu%','LIKE') ,
    	 *		)			
    	 *	);
    	 *	
    	 *	Zend_Custom_Core::dump($sql_cond) ;
    	 *  // 显示: (  first_name = 'iamsese' AND age >= 18 OR grade > 72 AND last_name LIKE '%kenxu%' )
    	 *	
    	 *	$game = new Game();
    	 *	
    	 *	$sql_cond = Zend_Custom_DB_TableDataGateway::getConditions(
    	 *		$game->getAdapter() ,
    	 *		array(
    	 *			'gamename' => array('%文%','LIKE') ,
    	 *		)			
    	 *	);
    	 *  // 显示: (  gamename LIKE '%文%' ) 
    	 *	
    	 *	$funabc = $game->get($sql_cond);
    	 *	Zend_Custom_Core::dump($funabc->toArray(),$sql_cond) ;
    	 *	
    	 * @param Zend_Db_Adapter_Abstract $dbAdapter db适配器对象
    	 * @param mixed $conditions 条件
    	 * @return string
    	 */
    	static function getConditions(Zend_Db_Adapter_Abstract $dbAdapter,$conditions){
    		
    		if (empty($conditions)) return '' ;
    		if (is_string($conditions)) return "( {$conditions} )" ;
    		if (is_array($conditions)) {
    
    			$text = '' ; $join = '' ;
    			foreach ($conditions as $fld => $cond){
    				if (is_object($cond)) continue ;
    				
    				$compare = "=" ; //缺省的比较符
    				
    				$noQuote = false ; //不进行转义字符操作 
    				
    				if (is_array($cond)){ // array(:value,:compare,:join,:noQuote)
    					
    					$value = array_shift($cond);
    					
    					if (is_object($value)) continue ;
    					
    					if ($_ = array_shift($cond)) // :compare
    						$compare = $_ ;
    						
    					if ($_ = array_shift($cond)) { // :join
    						if ($join) // 第一次无须连接符号
    							$join = $_ ;
    					}
    						
    					if ($_ = array_shift($cond) ) // :noQuote
    						$noQuote = true ;
    						
    				} else {
    					$value = $cond ;
    				}
    						
    				if ($noQuote) {
    					
    					$value = is_array($value) ? '(' . implode(',',$value) . ')' : $value ;
    					$_ = "{$fld} {$compare} {$value}" ;
    					
    				} else {
    					// 参数占位符
    					$paramQM = is_array($value) ? '(?)' : '?' ;
    					$_ = $dbAdapter->quoteInto("{$fld} {$compare} {$paramQM}",$value);
    				}
    
    				$text .= " {$join} {$_}" ;
    				
    				$join = 'AND' ;
    			}
    			
    			return "({$text} )" ;
    		}
    		return '' ;	
    	}
    
    

评论功能维护中,当前仅展示历史评论。