PHP链式调用
2017-09-25 本文已影响42人
零一间
第一种方式
<?php
/**
* PHP 链式调用构造一个查询语句
* Class Mysql
*/
class Mysql {
//SQL语句
private $sql = 'SELECT';
/**
* 数据库初始化
* @param array $config 配置项
*/
public function __construct(array $config) {
//逻辑处理
}
/**
* 查询字段
* @param $fields
* @return $this
*/
public function fields($fields) {
$this->sql .= ' ' . $fields;
return $this;
}
/**
* 操作表
* @param $table
* @return $this
*/
public function table($table) {
$this->sql .= ' FROM ' . $table;
return $this;
}
/**
* where条件
* @param $where
* @return $this
*/
public function where($where) {
$this->sql .= ' WHERE ' . $where;
return $this;
}
/**
* 排序
* @param $order
* @return $this
*/
public function order($order) {
$this->sql .= ' ORDER BY ' . $order;
return $this;
}
/**
* limit限制
* @param $limit
* @return $this
*/
public function limit($limit) {
$this->sql .= ' LIMIT ' . $limit;
return $this;
}
/**
* 构造SQL
* @return string SQL语句
*/
public function buildSql() {
return $this->sql;
}
}
$mysqlObj = new Mysql(array());
$retSql = $mysqlObj
->fields('*')
->table('bi_company')
->where("`product_id` = 'A001' AND `is_del` = '0'")
->order('`company_id` DESC')
->limit('0, 50')
->buildSql();
echo '生成SQL:'.$retSql;
//生成SQL:SELECT * FROM bi_company WHERE `product_id` = 'A001' AND `is_del` = '0' ORDER BY `company_id` DESC LIMIT 0, 50