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下将XML转换为数组
Jan 01 PHP
PHP 日志缩略名的创建函数代码
May 26 PHP
《PHP编程最快明白》第七讲:php图片验证码与缩略图
Nov 01 PHP
使用PHP生成二维码的方法汇总
Jul 22 PHP
mysql查找删除重复数据并只保留一条实例详解
Sep 24 PHP
php格式化时间戳
Dec 17 PHP
[原创]PHP实现字节数Byte转换为KB、MB、GB、TB的方法
Aug 31 PHP
PHP 传输会话curl函数的实例详解
Sep 12 PHP
CodeIgniter框架钩子机制实现方法【hooks类】
Aug 21 PHP
PHP实现cookie跨域session共享的方法分析
Aug 23 PHP
mysqli扩展无法在PHP7下升级问题的解决
Sep 10 PHP
PHP实现基本留言板功能原理与步骤详解
Mar 26 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
php中eval函数的危害与正确禁用方法
2014/06/30 PHP
php 类自动载入的方法
2015/06/03 PHP
PHP实现对二维数组某个键排序的方法
2016/09/14 PHP
php实现留言板功能
2017/03/05 PHP
一款Jquery 分页插件的改造方法(服务器端分页)
2011/07/11 Javascript
用jquery方法操作radio使其默认选项是否
2013/09/10 Javascript
给ListBox添加双击事件示例代码
2013/12/02 Javascript
node-webkit打包成exe文件被360误报木马的解决方法
2015/03/11 Javascript
js设置document.domain实现跨域的注意点分析
2015/05/21 Javascript
XML文件转化成NSData对象的方法
2015/08/12 Javascript
关注jquery技巧提高jquery技能(前端开发必学)
2015/11/02 Javascript
记一次webpack3升级webpack4的踩坑经历
2018/06/12 Javascript
Vue列表渲染的示例代码
2018/11/01 Javascript
vue实现的仿淘宝购物车功能详解
2019/01/27 Javascript
jQuery访问json文件中数据的方法示例
2019/01/28 jQuery
如何在微信小程序中实现Mixins方案
2019/06/20 Javascript
Vue中点击active并第一个默认选中功能的实现
2020/02/24 Javascript
[57:31]DOTA2-DPC中国联赛 正赛 SAG vs CDEC BO3 第一场 2月1日
2021/03/11 DOTA
简单文件操作python 修改文件指定行的方法
2013/05/15 Python
利用打码兔和超人打码自封装的打码类分享
2014/03/16 Python
Python subprocess模块常见用法分析
2018/06/12 Python
Django + Uwsgi + Nginx 实现生产环境部署的方法
2018/06/20 Python
Python实现的绘制三维双螺旋线图形功能示例
2018/06/23 Python
Pycharm 设置默认头的图文教程
2019/01/17 Python
numpy.linspace函数具体使用详解
2019/05/27 Python
python实现银行实战系统
2020/02/26 Python
Python爬虫实现自动登录、签到功能的代码
2020/08/20 Python
Python实现钉钉/企业微信自动打卡的示例代码
2021/02/02 Python
使用HTML5的链接预取功能(link prefetching)给网站提速
2012/12/13 HTML / CSS
C#如何调用Word并打开一个Word文档
2013/05/08 面试题
高中毕业生自我鉴定
2013/11/03 职场文书
高中班主任评语大全
2014/04/25 职场文书
农行心得体会
2014/09/02 职场文书
2016廉洁从业学习心得体会
2016/01/19 职场文书
left join、inner join、right join的区别
2021/04/05 MySQL
Django框架之路由用法
2022/06/10 Python