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 禁止页面缓存输出
Jan 07 PHP
Godaddy空间Zend Optimizer升级方法
May 10 PHP
codeigniter上传图片不能正确识别图片类型问题解决方法
Jul 25 PHP
推荐一款PHP+jQuery制作的列表分页的功能模块
Oct 14 PHP
php随机取mysql记录方法小结
Dec 27 PHP
php array_values 返回数组的所有值详解及实例
Nov 12 PHP
PHP实现获取第一个中文首字母并进行排序的方法
May 09 PHP
php实现网页端验证码功能
Jul 11 PHP
PHP基于rabbitmq操作类的生产者和消费者功能示例
Jun 16 PHP
php 处理png图片白色背景色改为透明色的实例代码
Dec 10 PHP
Laravel配置全局公共函数的方法步骤
May 09 PHP
php基于 swoole 实现的异步处理任务功能示例
Aug 13 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
DC动画很好看?新作烂得令人发指,名叫《红色之子》
2020/04/09 欧美动漫
php REMOTE_ADDR之获取访客IP的代码
2008/04/22 PHP
解析thinkphp的左右值无限分类
2013/06/20 PHP
PHP面向对象五大原则之接口隔离原则(ISP)详解
2018/04/04 PHP
取得传值的函数
2006/10/27 Javascript
比较详细的javascript对象的property和prototype是什么一种关系
2007/08/06 Javascript
jQuery中读取json文件示例代码
2013/05/10 Javascript
教你如何自定义百度分享插件以及bshare分享插件的分享按钮
2014/06/20 Javascript
javascript原型继承工作原理和实例详解
2016/04/07 Javascript
javascript的几种写法总结
2016/09/30 Javascript
vue.js国际化 vue-i18n插件的使用详解
2017/07/07 Javascript
vue做网页开场视频的实例代码
2017/10/20 Javascript
axios简单实现小程序延时loading指示
2018/07/30 Javascript
vue弹窗插件实战代码
2018/09/08 Javascript
node+express框架中连接使用mysql(经验总结)
2018/11/10 Javascript
JS基于开关思想实现的数组去重功能【案例】
2019/02/18 Javascript
vue使用openlayers实现移动点动画
2020/09/24 Javascript
[41:08]2014 DOTA2国际邀请赛中国区预选赛 HGT VS NE
2014/05/22 DOTA
[02:44]2014DOTA2 国际邀请赛中国区预选赛 大神红毯秀
2014/05/25 DOTA
python数据挖掘需要学的内容
2019/06/23 Python
python中图像通道分离与合并实例
2020/01/17 Python
Python如何读取、写入CSV数据
2020/07/28 Python
挪威手表购物网站:Klokker
2016/09/19 全球购物
巴西图书和电子产品购物网站:Saraiva
2017/06/07 全球购物
美国婚礼和派对礼品网站:Kate Aspen(新娘送礼会、迎婴派对)
2018/03/28 全球购物
社会实践自我鉴定
2013/11/07 职场文书
应届护士推荐信
2013/11/16 职场文书
酒店副总岗位职责
2013/12/24 职场文书
银行职业规划书范文
2013/12/28 职场文书
护士辞职信范文
2014/01/19 职场文书
综合内勤岗位职责
2014/04/14 职场文书
信仰心得体会
2014/09/05 职场文书
法定代表人授权委托书范文
2014/09/22 职场文书
中秋节祝酒词
2015/08/12 职场文书
继续教育心得体会(共6篇)
2016/01/19 职场文书
my.ini优化mysql数据库性能的十个参数(推荐)
2021/05/26 MySQL