PHP实现的MongoDB数据库操作类分享


Posted in PHP onMay 12, 2014
class HMongodb {   

  private $mongo;  //Mongodb连接
  private $curr_db_name;
  private $curr_table_name;
  private $error;   

  public function getInstance($mongo_server, $flag=array())
  {
    static $mongodb_arr;
    if (empty($flag['tag']))
    {
      $flag['tag'] = 'default';     }
    if (isset($flag['force']) && $flag['force'] == true)
    {
      $mongo = new HMongodb($mongo_server);
      if (empty($mongodb_arr[$flag['tag']])) 
      {
        $mongodb_arr[$flag['tag']] = $mongo;
      }
      return $mongo;
    }
    else if (isset($mongodb_arr[$flag['tag']]) && is_resource($mongodb_arr[$flag['tag']]))
    {
      return $mongodb_arr[$flag['tag']];
    }
    else
    {
      $mongo = new HMongodb($mongo_server);
      $mongodb_arr[$flag['tag']] = $mongo;
      return $mongo;
    }
  }

  /**
   * 构造函数
   * 支持传入多个mongo_server(1.一个出问题时连接其它的server 2.自动将查询均匀分发到不同server)
   *
   * 参数:
   * $mongo_server:数组或字符串-array("127.0.0.1:1111", "127.0.0.1:2222")-"127.0.0.1:1111"
   * $connect:初始化mongo对象时是否连接,默认连接
   * $auto_balance:是否自动做负载均衡,默认是
   *
   * 返回值:
   * 成功:mongo object
   * 失败:false
   */
  private function __construct($mongo_server, $connect=true, $auto_balance=true)
  {
   if (is_array($mongo_server))
   {
   $mongo_server_num = count($mongo_server);
   if ($mongo_server_num > 1 && $auto_balance)
   {
    $prior_server_num = rand(1, $mongo_server_num);
    $rand_keys = array_rand($mongo_server,$mongo_server_num);
    $mongo_server_str = $mongo_server[$prior_server_num-1];
    foreach ($rand_keys as $key)
    {
    if ($key != $prior_server_num - 1)
    {
     $mongo_server_str .= ',' . $mongo_server[$key];
    }
    }
   }
   else
   {
    $mongo_server_str = implode(',', $mongo_server);
   }         }
   else
   {
    $mongo_server_str = $mongo_server;
   }
   try {
    $this->mongo = new Mongo($mongo_server, array('connect'=>$connect));
   }
   catch (MongoConnectionException $e)
   {
    $this->error = $e->getMessage();
    return false;
   }
  }

  /**
  * 连接mongodb server
  *
  * 参数:无
  *
  * 返回值:
  * 成功:true
  * 失败:false
  */
  public function connect()
  {
    try {
      $this->mongo->connect();
      return true;
    }
    catch (MongoConnectionException $e)
    {
      $this->error = $e->getMessage();
      return false;
    }
  }   

  /**
  * select db
  *
  * 参数:$dbname
  *
  * 返回值:无
  */
  public function selectDb($dbname)
  {
    $this->curr_db_name = $dbname;
  }   

  /**
  * 创建索引:如索引已存在,则返回。
  *
  * 参数:
  * $table_name:表名
  * $index:索引-array("id"=>1)-在id字段建立升序索引
  * $index_param:其它条件-是否唯一索引等
  *
  * 返回值:
  * 成功:true
  * 失败:false
  */
  public function ensureIndex($table_name, $index, $index_param=array())
  {
    $dbname = $this->curr_db_name;
    $index_param['safe'] = 1;
    try {
      $this->mongo->$dbname->$table_name->ensureIndex($index, $index_param);
      return true;
    }
    catch (MongoCursorException $e)
    {
      $this->error = $e->getMessage();
      return false;
    }
  }

  /**
  * 插入记录
  *
  * 参数:
  * $table_name:表名
  * $record:记录
  *
  * 返回值:
  * 成功:true
  * 失败:false
  */
  public function insert($table_name, $record)
  {
    $dbname = $this->curr_db_name;
    try {
      $this->mongo->$dbname->$table_name->insert($record, array('safe'=>true));
      return true;
    }
    catch (MongoCursorException $e)
    {
      $this->error = $e->getMessage();
      return false;
    }
  }   

  /**
  * 查询表的记录数
  *
  * 参数:
  * $table_name:表名
  *
  * 返回值:表的记录数
  */
  public function count($table_name)
  {
    $dbname = $this->curr_db_name;
    return $this->mongo->$dbname->$table_name->count();
  }   

  /**
  * 更新记录
  *
  * 参数:
  * $table_name:表名
  * $condition:更新条件
  * $newdata:新的数据记录
  * $options:更新选择-upsert/multiple
  *
  * 返回值:
  * 成功:true
  * 失败:false
  */
  public function update($table_name, $condition, $newdata, $options=array())
  {
    $dbname = $this->curr_db_name;
    $options['safe'] = 1;
    if (!isset($options['multiple']))
    {
      $options['multiple'] = 0;     }
    try {
      $this->mongo->$dbname->$table_name->update($condition, $newdata, $options);
      return true;
    }
    catch (MongoCursorException $e)
    {
      $this->error = $e->getMessage();
      return false;
    }
  }   

  /**
  * 删除记录
  *
  * 参数:
  * $table_name:表名
  * $condition:删除条件
  * $options:删除选择-justOne
  *
  * 返回值:
  * 成功:true
  * 失败:false
  */
  public function remove($table_name, $condition, $options=array())
  {
    $dbname = $this->curr_db_name;
    $options['safe'] = 1;
    try {
      $this->mongo->$dbname->$table_name->remove($condition, $options);
      return true;
    }
    catch (MongoCursorException $e)
    {
      $this->error = $e->getMessage();
      return false;
  }  }   

  /**
  * 查找记录
  *
  * 参数:
  * $table_name:表名
  * $query_condition:字段查找条件
  * $result_condition:查询结果限制条件-limit/sort等
  * $fields:获取字段
  *
  * 返回值:
  * 成功:记录集
  * 失败:false
  */
  public function find($table_name, $query_condition, $result_condition=array(), $fields=array())
  {
    $dbname = $this->curr_db_name;
    $cursor = $this->mongo->$dbname->$table_name->find($query_condition, $fields);
    if (!empty($result_condition['start']))
    {
      $cursor->skip($result_condition['start']);
    }
    if (!empty($result_condition['limit']))
    {
      $cursor->limit($result_condition['limit']);
    }
    if (!empty($result_condition['sort']))
    {
      $cursor->sort($result_condition['sort']);
    }
    $result = array();
    try {
      while ($cursor->hasNext())
      {
        $result[] = $cursor->getNext();
      }
    }
    catch (MongoConnectionException $e)
    {
      $this->error = $e->getMessage();
      return false;
    }
    catch (MongoCursorTimeoutException $e)
    {
      $this->error = $e->getMessage();
      return false;
    }
    return $result;
  }   

  /**
  * 查找一条记录
  *
  * 参数:
  * $table_name:表名
  * $condition:查找条件
  * $fields:获取字段
  *
  * 返回值:
  * 成功:一条记录
  * 失败:false
  */
  public function findOne($table_name, $condition, $fields=array())
  {
    $dbname = $this->curr_db_name;
    return $this->mongo->$dbname->$table_name->findOne($condition, $fields);
  }   

  /**
  * 获取当前错误信息
  *
  * 参数:无
  *
  * 返回值:当前错误信息
  */
  public function getError()
  {
    return $this->error;
  }

  /*** Mongodb类** examples:
   * $mongo = new HMongodb("127.0.0.1:11223");
  * $mongo->selectDb("test_db");
  * 创建索引
  * $mongo->ensureIndex("test_table", array("id"=>1), array('unique'=>true));
  * 获取表的记录
  * $mongo->count("test_table");
  * 插入记录
  * $mongo->insert("test_table", array("id"=>2, "title"=>"asdqw"));
  * 更新记录
  * $mongo->update("test_table", array("id"=>1),array("id"=>1,"title"=>"bbb"));
  * 更新记录-存在时更新,不存在时添加-相当于set
  * $mongo->update("test_table", array("id"=>1),array("id"=>1,"title"=>"bbb"),array("upsert"=>1));
  * 查找记录
  * $mongo->find("c", array("title"=>"asdqw"), array("start"=>2,"limit"=>2,"sort"=>array("id"=>1)))
  * 查找一条记录
  * $mongo->findOne("$mongo->findOne("ttt", array("id"=>1))", array("id"=>1));
  * 删除记录
  * $mongo->remove("ttt", array("title"=>"bbb"));
  * 仅删除一条记录
  * $mongo->remove("ttt", array("title"=>"bbb"), array("justOne"=>1));
  * 获取Mongo操作的错误信息
  * $mongo->getError();
  */

}
PHP 相关文章推荐
php中文字符截取防乱码
Mar 28 PHP
使用VisualStudio开发php的图文设置方法
Aug 21 PHP
页面乱码问题的根源及其分析
Aug 09 PHP
php使用date和strtotime函数输出指定日期的方法
Nov 14 PHP
PHP中余数、取余的妙用
Jun 29 PHP
php精确的统计在线人数的方法
Oct 21 PHP
php socket通信(tcp/udp)实例分析
Feb 14 PHP
PHP创建/删除/复制文件夹、文件
May 03 PHP
phpmailer简单发送邮件的方法(附phpmailer源码下载)
Jun 13 PHP
PHP两种实现无级递归分类的方法
Mar 02 PHP
PHP实现类似题库抽题效果
Aug 16 PHP
YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用示例
Mar 18 PHP
PHP中date与gmdate的区别及默认时区设置
May 12 #PHP
PHP三元运算的2种写法代码实例
May 12 #PHP
PHP入门之常量简介和系统常量
May 12 #PHP
PHP实现数字补零功能的2个函数介绍
May 12 #PHP
PHP生成迅雷、快车、旋风等软件的下载链接代码实例
May 12 #PHP
phpMyAdmin自动登录和取消自动登录的配置方法
May 12 #PHP
PHP.ini中配置屏蔽错误信息显示和保存错误日志的例子
May 12 #PHP
You might like
MySQL数据源表结构图示
2008/06/05 PHP
php curl_init函数用法
2014/01/31 PHP
PHP根据IP判断地区名信息的示例代码
2014/03/03 PHP
使用symfony命令创建项目的方法
2016/03/17 PHP
smarty循环嵌套用法示例分析
2016/07/19 PHP
php语法检查的方法总结
2019/01/21 PHP
利用location.hash实现跨域iframe自适应
2010/05/04 Javascript
jQuery使用fadein方法实现渐出效果实例
2015/03/27 Javascript
jQuery表单美化插件jqTransform使用详解
2015/04/12 Javascript
js实现Form栏显示全格式时间时钟效果代码
2015/08/19 Javascript
详解JavaScript的表达式与运算符
2015/11/30 Javascript
jQuery简单注册和禁用全局事件的方法
2016/07/25 Javascript
微信小程序 登录实例详解
2017/01/16 Javascript
vue中component组件的props使用详解
2017/09/04 Javascript
深入理解 TypeScript Reflect Metadata
2019/12/12 Javascript
JS window对象简单操作完整示例
2020/01/14 Javascript
浅谈在vue-cli3项目中解决动态引入图片img404的问题
2020/08/04 Javascript
python网络编程学习笔记(四):域名系统
2014/06/09 Python
Python中非常实用的一些功能和函数分享
2015/02/14 Python
python selenium UI自动化解决验证码的4种方法
2018/01/05 Python
解决使用pycharm提交代码时冲突之后文件丢失找回的方法
2018/08/05 Python
python文件写入write()的操作
2019/05/14 Python
Python字符串大小写转换拼接删除空白
2019/09/19 Python
3D动画《斗罗大陆》上线当日播放过亿
2021/03/16 国漫
如何查看浏览器对html5的支持情况
2020/12/15 HTML / CSS
给领导的致歉信范文
2014/01/13 职场文书
10的分与合教学反思
2014/04/30 职场文书
分公司经理任命书
2014/06/05 职场文书
团队口号大全
2014/06/06 职场文书
中秋晚会活动方案
2014/08/31 职场文书
学习优秀党员杨宗兴先进事迹材料思想汇报
2014/09/14 职场文书
2014年测量员工作总结
2014/12/12 职场文书
处世之道:关于真诚相待的名言推荐
2019/12/02 职场文书
SpringAop日志找不到方法的处理
2021/06/21 Java/Android
JavaScript高级程序设计之变量与作用域
2021/11/17 Javascript
docker-compose部署Yapi的方法
2022/04/08 Servers