php实现带读写分离功能的MySQL类完整实例


Posted in PHP onJuly 28, 2016

本文实例讲述了php实现带读写分离功能的MySQL类。分享给大家供大家参考,具体如下:

概述:

1. 根据sql语句判断是连接读库还是写库
2. 链式调用$this->where()->get()
3. 不同的主机对应不同的实例, 不再多次new

具体代码如下:

<?php
class DBRWmysql
{
  private static $Instance = null;
  private $links = array();//链接数组
  private $link = null; //当前连接
  public $dbType = 'read';
  public $_host=''; //数据库所在主机名
  public $_database = '';//当前数据库名
  public $_tablename = '';//当前表的表名
  public $_dt ='';//database.tablename
  public $isRelease = 0; //查询完成后是否释放
  public $fields = '*';
  public $arrWhere = [];
  public $order = '';
  public $arrOrder = [];
  public $limit = '';
  public $sql = '';
  public $rs;//结果集
  private function __construct($database='', $tablename='', $isRelease=0)
  {
    $this->_database = $database;//database name
    $this->_tablename = $tablename;//table name
    $this->_dt = "`{$this->_database}`.`{$this->_tablename}`";
    $this->isRelease = $isRelease;
  }
  public static function getInstance($database='', $tablename='', $isRelease=0)
  {
    if (self::$Instance == null) {
      self::$Instance = new DBRWmysql($database, $tablename, $isRelease);
    }
    self::$Instance->_database = $database;
    self::$Instance->_tablename = $tablename;
    self::$Instance->_dt    = "`{$database}`.`{$tablename}`";
    self::$Instance->isRelease = $isRelease;
    return self::$Instance;
  }
  //如果主机没变,并且已经存在MYSQL连接,就不再创建新的连接
  //如果主机改变,就再生成一个实例创建一个连接
  //type == 'write'或'read'
  public function getLink($type)
  {
    $this->dbType = $$type;
    //随机选取一个数据库连接(区分读写)
    $dbConfig = DBConfig::$$type;
    $randKey = array_rand($dbConfig);
    $config = $dbConfig[$randKey];
    //链接数据库
    $host = $config['host'];
    $username = $config['username'];
    $password = $config['password'];
    if (empty($this->links[$host])) {
      $this->_host = $host;
      $this->links[$host] = new mysqli($host, $username, $password);
      if($this->links[$host]->connect_error) {
        $this->error($this->links[$host]->connect_error);
      }
    }
    //初始化链接
    $this->link = $this->links[$host];
    $this->link->query("set names utf8mb4;"); //支持emoji表情
    $this->link->query("use {$this->_database};");
  }
  public function getCurrentLinks()
  {
    return $this->links;
  }
  //析构函数
  public function __destruct()
  {
    foreach ($this->links as $v) {
      $v->close();
    }
  }
  //查询封装
  public function query($sql)
  {
    $this->sql = $sql;
    if (strpos($sql, 'select') !== false) {
      $this->getLink('read');//读库
    } else {
      $this->getLink('write');//写库
    }
    $this->rs = $this->link->query($sql);
    ($this->rs === false) && $this->error('sql error: '.$sql.PHP_EOL.$this->link->error);
    //查询完成后释放链接, 并删除链接对象
    if ($this->isRelease) {
      $this->link->close();
      unset($this->links[$this->_host]);
    }
    return $this->rs;
  }
  //增
  public function insert($arrData)
  {
    foreach ($arrData as $key=>$value) {
      $fields[] = $key;
      $values[] = "'".$value."'";
      // $fields[] = '`'.$key.'`';
      // $values[] = "'".$value."'";
    }
    $strFields = implode(',', $fields);
    $strValues = implode(',', $values);
    $sql = "insert into {$this->_dt} ($strFields) values ($strValues)";
    $this->query($sql);
    $insert_id = $this->link->insert_id;
    return $insert_id;
  }
  //增
  public function replace($arrData)
  {
    foreach ($arrData as $key=>$value) {
      $fields[] = $key;
      $values[] = "'{$value}'";
    }
    $strFields = implode(',', $fields);
    $strValues = implode(',', $values);
    $sql = "replace into {$this->_dt} ($strFields) values ($strValues)";
    $this->query($sql);
    return $this->link->insert_id;
  }
  //增
  //每次插入多条记录
  //每条记录的字段相同,但是值不一样
  public function insertm($arrFields, $arrData)
  {
    foreach ($arrFields as $v) {
      // $fields[] = "`{$v}`";
      $fields[] = $v;
    }
    foreach ($arrData as $v) {
      $data[] = '('.implode(',', $v).')';
    }
    $strFields = implode(',', $fields);
    $strData = implode(',', $data);
    $sql = "insert into {$this->_dt} ($strFields) values {$strData}";
    $this->query($sql);
    return $this->link->insert_id;
  }
  //删
  public function delete()
  {
    $where = $this->getWhere();
    $limit = $this->getLimit();
    $sql = " delete from {$this->_dt} {$where} {$limit}";
    $this->query($sql);
    return $this->link->affected_rows;
  }
  //改
  public function update($data)
  {
    $where = $this->getWhere();
    $arrSql = array();
    foreach ($data as $key=>$value) {
      $arrSql[] = "{$key}='{$value}'";
    }
    $strSql = implode(',', $arrSql);
    $sql = "update {$this->_dt} set {$strSql} {$where} {$this->limit}";
    $this->query($sql);
    return $this->link->affected_rows;
  }
  //获取总数
  public function getCount()
  {
    $where = $this->getWhere();
    $sql = " select count(1) as n from {$this->_dt} {$where} ";
    $resault = $this->query($sql);
    ($resault===false) && $this->error('getCount error: '.$sql);
    $arrRs = $this->rsToArray($resault);
    $num = array_shift($arrRs);
    return $num['n'];
  }
  //将结果集转换成数组返回
  //如果field不为空,则返回的数组以$field为键重新索引
  public function rsToArray($field = '')
  {
    $arrRs = $this->rs->fetch_all(MYSQLI_ASSOC); //该函数只能用于php的mysqlnd驱动
    $this->rs->free();//释放结果集
    if ($field) {
      $arrResult = [];
      foreach ($arrRs as $v) {
        $arrResult[$v[$field]] = $v;
      }
      return $arrResult;
    }
    return $arrRs;
  }
  //给字段名加上反引号
  public function qw($strFields)
  {
    $strFields = preg_replace('#\s+#', ' ', $strFields);
    $arrNewFields = explode(' ', $strFields );
    $arrNewFields = array_filter($arrNewFields);
    foreach ($arrNewFields as $k => $v) {
      $arrNewFields[$k]= '`'.$v.'`';
    }
    return implode(',', $arrNewFields);
  }
  //处理入库数据,将字符串格式的数据转换为...格式(未实现)
  public function getInsertData($strData)
  {
    // $bmap = "jingdu,$jingdu weidu,$weidu content,$content";
  }
  //select in
  //arrData 整数数组,最好是整数
  public function select_in($key, $arrData, $fields='')
  {
    $fields = $fields ? $fields : '*';
    sort($arrData);
    $len = count($arrData);
    $cur = 0;
    $pre = $arrData[0];
    $new = array('0' => array($arrData[0]));
    for ($i = 1; $i < $len; $i++) {
      if (($arrData[$i] - $pre) == 1 ) {
        $new[$cur][] = $arrData[$i];
      } else {
        $cur = $i;
        $new[$cur][] = $arrData[$i];
      }
      $pre = $arrData[$i];
    }
    $arrSql = array();
    foreach ($new as $v) {
      $len = count($v) - 1;
      if ($len) {
        $s = $v[0];
        $e = end($v);
        $sql = "(select $fields from {$this->_dt} where $key between $s and $e)";
      } else {
        $s = $v[0];
        $sql = "(select $fields from {$this->_dt} where $key = $s)";
      }
      $arrSql[] = $sql;
    }
    $strUnion = implode(' UNION ALL ', $arrSql);
    $res = $this->query($strUnion);
    return $this->rstoarray($res);
  }
  //where in
  public function setWhereIn($key, $arrData)
  {
    if (empty($arrData)) {
      $str = "(`{$key}` in ('0'))";
      $this->addWhere($str);
      return $str;
    }
    foreach ($arrData as &$v) {
      $v = "'{$v}'";
    }
    $str = implode(',', $arrData);
    $str = "(`{$key}` in ( {$str} ))";
    $this->addWhere($str);
    return $this;
  }
  //where in
  public function setWhere($arrData)
  {
    if (empty($arrData)) {
      return '';
    }
    foreach ($arrData as $k => $v) {
      $str = "(`{$k}` = '{$v}')";
      $this->addWhere($str);
    }
    return $this;
  }
  //between and
  public function setWhereBetween($key, $min, $max)
  {
    $str = "(`{$key}` between '{$min}' and '{$max}')";
    $this->addWhere($str);
    return $this;
  }
  //where a>b
  public function setWhereBT($key, $value)
  {
    $str = "(`{$key}` > '{$value}')";
    $this->addWhere($str);
    return $this;
  }
  //where a<b
  public function setWhereLT($key, $value)
  {
    $str = "(`{$key}` < '{$value}')";
    $this->addWhere($str);
    return $this;
  }
  //组装where条件
  public function addWhere($where)
  {
    $this->arrWhere[] = $where;
  }
  //获取最终查询用的where条件
  public function getWhere()
  {
    if (empty($this->arrWhere)) {
      return 'where 1';
    } else {
      return 'where '.implode(' and ', $this->arrWhere);
    }
  }
  //以逗号隔开
  public function setFields($fields)
  {
    $this->fields = $fields;
    return $this;
  }
  // order by a desc
  public function setOrder($order)
  {
    $this->arrOrder[] = $order;
    return $this;
  }
  //获取order语句
  public function getOrder()
  {
    if (empty($this->arrOrder)) {
      return '';
    } else {
      $str = implode(',', $this->arrOrder);
      $this->order = "order by {$str}";
    }
    return $this->order;
  }
  //e.g. '0, 10'
  //用limit的时候可以加where条件优化:select ... where id > 1234 limit 0, 10
  public function setLimit($limit)
  {
    $this->limit = 'limit '.$limit;
    return $this;
  }
  //直接查询sql语句, 返回数组格式
  public function arrQuery($sql, $field='')
  {
    $this->query($sql);
    $this->clearQuery();
    ($this->rs===false) && $this->error('select error: '.$sql);
    return $this->rsToArray($field);
  }
  //如果 $field 不为空, 则返回的结果以该字段的值为索引
  //暂不支持join
  public function get($field='')
  {
    $where = $this->getWhere();
    $order = $this->getOrder();
    $sql = " select {$this->fields} from {$this->_dt} {$where} {$order} {$this->limit} ";
    return $this->arrQuery($sql, $field);
  }
  //获取一条记录
  public function getOne()
  {
    $this->setLimit(1);
    $rs = $this->get();
    return !empty($rs) ? $rs[0] : [];
  }
  //获取一条记录的某一个字段的值
  public function getOneField($field)
  {
    $this->setFields($field);
    $rs = $this->getOne();
    return !empty($rs[$field]) ? $rs[$field] : '';
  }
  //获取数据集中所有某个字段的值
  public function getFields($field)
  {
    $this->setFields($field);
    $rs = $this->get();
    $result = [];
    foreach ($rs as $v) {
      $result[] = $v[$field];
    }
    unset($rs);
    return $result;
  }
  //清除查询条件
  //防止干扰下次查询
  public function clearQuery()
  {
    $this->fields = '*';
    $this->arrWhere = [];
    $this->order = '';
    $this->arrOrder = [];
    $this->limit = '';
  }
  //断开数据库连接
  public function close()
  {
    $this->link->close();
  }
  //事务
  //自动提交开关
  public function autocommit($bool)
  {
    $this->link->autocommit($bool);
  }
  //事务完成提交
  public function commit()
  {
    $this->link->commit();
  }
  //回滚
  public function rollback()
  {
    $this->link->rollback();
  }
  //输出错误sql语句
  public function error($sql)
  {
    //if (IS_TEST) {}
    exit($sql);
  }
}

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP 和 MySQL 开发的 8 个技巧
Jan 02 PHP
IIS6的PHP最佳配置方法
Mar 19 PHP
php visitFile()遍历指定文件夹函数
Aug 21 PHP
apache+php完美解决301重定向的两种方法
Jun 08 PHP
PHPExcel读取Excel文件的实现代码
Dec 06 PHP
在PHP中运行Linux命令并启动SSH服务的例子
Jun 12 PHP
php实现递归与无限分类的方法
Feb 16 PHP
PHP 生成微信红包代码简单
Mar 25 PHP
yii2实现根据时间搜索的方法
May 25 PHP
PHP生成推广海报的方法分享
Apr 22 PHP
PHP生成(支持多模板)二维码海报代码
Apr 30 PHP
PHP的curl函数的用法总结
Feb 14 PHP
PHP实现带重试功能的curl连接示例
Jul 28 #PHP
php使用strip_tags()去除html标签仍有空白的解决方法
Jul 28 #PHP
php倒计时出现-0情况的解决方法
Jul 28 #PHP
24条货真价实的PHP代码优化技巧
Jul 28 #PHP
php求今天、昨天、明天时间戳的简单实现方法
Jul 28 #PHP
php字符串操作针对负值的判断分析
Jul 28 #PHP
PHP实现bitmap位图排序与求交集的方法
Jul 28 #PHP
You might like
PHP 增加了对 .ZIP 文件的读取功能
2006/10/09 PHP
php侧拉菜单 漂亮,可以向右或者向左展开,支持FF,IE
2009/10/15 PHP
PHP大批量数据操作时临时调整内存与执行时间的方法
2011/04/20 PHP
PHP 抽象方法与抽象类abstract关键字介绍及应用
2014/10/16 PHP
Yii2框架数据验证操作实例详解
2018/05/02 PHP
Apply an AutoFormat to an Excel Spreadsheet
2007/06/12 Javascript
基于jQuery的可用于选项卡及幻灯的切换插件
2011/03/28 Javascript
DOM 高级编程
2015/05/06 Javascript
javascript检测移动设备横竖屏
2016/05/21 Javascript
js模拟支付宝密码输入框
2017/04/11 Javascript
基于Bootstrap模态对话框只加载一次 remote 数据的解决方法
2017/07/09 Javascript
Vue仿手机qq的实例代码(demo)
2017/09/08 Javascript
解决vue单页使用keep-alive页面返回不刷新的问题
2018/03/13 Javascript
vue+node实现图片上传及预览的示例方法
2018/11/22 Javascript
微信小程序实现点击图片旋转180度并且弹出下拉列表
2018/11/27 Javascript
layui富文本编辑器前端无法取值的解决方法
2019/09/18 Javascript
[02:15]2015国际邀请赛选手档案IG.Ferrari 430
2015/07/30 DOTA
[01:32]DOTA2上海特锦赛现场采访:最想COS的英雄
2016/03/25 DOTA
python连接MySQL数据库实例分析
2015/05/12 Python
总结Python中逻辑运算符的使用
2015/05/13 Python
Python实现绘制双柱状图并显示数值功能示例
2018/06/23 Python
python traceback捕获并打印异常的方法
2018/08/31 Python
opencv3/python 鼠标响应操作详解
2019/12/11 Python
利用PyCharm操作Github(仓库新建、更新,代码回滚)
2019/12/18 Python
Python的logging模块基本用法
2020/12/24 Python
Origins悦木之源英国官网:雅诗兰黛集团高端植物护肤品牌
2017/11/06 全球购物
Clarks西班牙官方在线商店:clarks鞋
2019/05/03 全球购物
万豪国际住宅与别墅集团:Homes & Villas by Marriott International
2020/10/08 全球购物
函授毕业生自我鉴定范文
2014/03/25 职场文书
工商企业管理专业自荐信范文
2014/04/12 职场文书
关爱残疾人演讲稿
2014/05/24 职场文书
教师节活动总结
2014/08/29 职场文书
师德先进个人材料
2014/12/20 职场文书
首都博物馆观后感
2015/06/05 职场文书
Java比较两个对象中全部属性值是否相等的方法
2021/08/07 Java/Android
MySQL约束超详解
2021/09/04 MySQL