在接口被实例化以后的每个方法中return 类本身就可以达到链式操作。
改善了写多行代码执行一次操作的缺点。
下面请看我的代码,若有疑问,请留言给我。
class Instance{
public static $db;
public $mysql=NULL;
private function Connect($host,$user,$pwd,$port=3306){
$this->mysql=mysqli_connect($host,$user,$pwd,$port) or die('Can not Connect Mysql!');
}
private function __construct(){}
private function __clone(){}
public static function getInstance($host,$user,$pwd,$port=3306){
if(!isset(self::$db)){
self::$db = new self;
self::$db->Connect($host,$user,$pwd,$port);
}
return self::$db;
}
}
interface SQL{
/**
* @param string $sql SQL语句
* @return mixed
*/
public function Query($sql);
/**
* @param array $condition 条件
* @return mixed
*/
public function Select($condition=array());
/**
* @param array $condition 条件
* @return mixed
*/
public function Where($condition=array());
/**
* @param array $condition 条件
* @return mixed
*/
public function Group($condition=array());
/**
* @param array $condition 条件
* @return mixed
*/
public function Limit($condition=array());
/**
* @param array $condition 条件
* @return mixed
*/
public function Order($condition=array());
/**
* @return mixed 关闭数据库连接
*/
public function Close();
}
class CoherentModel implements SQL{
private $db; //数据库资源
protected $sql; //SQL语句
protected $result; //结果
public function __construct($db){
if(empty($db->mysql)){
exit('db not connected !');
}
$this->db=$db->mysql;
}
public function Query($sql=''){
$this->sql=$sql;
$this->result=mysqli_query($this->db,$sql);
return $this->result;
}
/**
* @param array $condition 条件
* @return mixed
*/
public function Select($condition=array()){
return $this;
}
/**
* @param array $condition 条件
* @return mixed
*/
public function Where($condition=array()){
return $this;
}
/**
* @param array $condition 条件
* @return mixed
*/
public function Group($condition=array()){
return $this;
}
/**
* @param array $condition 条件
* @return mixed
*/
public function Limit($condition=array()){
return $this;
}
/**
* @param array $condition 条件
* @return mixed
*/
public function Order($condition=array()){
return $this;
}
/**
* @return mixed 关闭数据库连接
*/
public function Close(){
mysqli_close($this->db);
}
}
/**
* 单例模式
*/
$Instance = Instance::getInstance('127.0.0.1','mysql','password');
$Model = new CoherentModel($Instance::$db);
/**
* 链式操作
*/
$Model->Where()->Group()->limit()->Select();