php操作MongoDB类实例

   2015-06-23 0
核心提示:这篇文章主要介绍了php操作MongoDB类的方法,实例分析了仿照CI实现的MongoDB类及其操作技巧,需要的朋友可以参考下

本文实例讲述了php操作MongoDB类的方法。分享给大家供大家参考。具体如下:

1. MyMongo.php文件:

<php
/**
 * 仿写CI的MongoDB
 * @author sparkHuang 2011-11-03
 *
 */
class MyMongo {
  private $mongo_config = "mongo_config.php";
  private $connection;
  private $db;
  private $mongo_connect_string;
  private $host;
  private $port;
  private $user;
  private $pass;
  private $dbname;
  private $persist;
  private $persist_key;
  private $selects = array();
  private $wheres = array();
  private $sorts = array();
  private $limit = 999999;
  private $offset = 0;
  public function __construct() {
    if ( ! class_exists('Mongo')) {
      $this->log_error("The MongoDB PECL extentiosn has not been installed or enabled.");
      exit;
    }
    
    $this->connection_string();
    $this->connect();
  }
  /**
   * 更改数据库
   *
   */
  public function switch_db($database = '') {
    if (empty($database)) {
      $this->log_error("To switch MongoDB databases, a new database name must be specified");
      exit;
    }
    $this->dbname = $database;
    try {
      $this->db = $this->connection->{$this->dbname};
      return true;
    } catch(Exception $e) {
      $this->log_error("Unable to switch Mongo Databases: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * 设置select字段
   *
   */
  public function select($includs = array(), $excludes = array()) {
    if ( ! is_array($includs)) {
      $includs = (array)$includs;
    }
    
    if ( ! is_array($excludes)) {
      $excludes = (array)$excludes;
    }
    
    if ( ! empty($includs)) {
      foreach ($includs as $col) {
        $this->selects[$col] = 1;
      }
    } else {
      foreach ($excludes as $col) {
        $this->selects[$col] = 0;
      }
    }
    
    return($this);
  }
  /**
   * where条件查询判断
   *
   * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');
   *
   */
  public function where($wheres = array()) {
    if ( ! is_array($wheres)) {
      $wheres = (array)$wheres;
    }
    
    if ( ! empty($wheres)) {
      foreach($wheres as $wh => $val) {
        $this->wheres[$wh] = $val;
      }
    }
    
    return($this);
  }
  /**
   * where ... in .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo'))->get('foobar');
   *
   */
  public function where_in($field = '', $in = array()) {
    $this->where_init($field);
    $this->wheres[$field]['$in'] = $in;
    return($this);
  }
  /**
   * where ... not in .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo'))->get('foobar');
   *
   */
  public function where_not_in($field = '', $in = array()) {
    $this->where_init($field);
    $this->wheres[$field]['$nin'] = $in;
    return($this);
  }
  /**
   * where ... $field > $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_gt('foo', 20)->get('foobar');
   *
   */
  public function where_gt($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$gt'] = $x;
    return($this);
  }
  /**
   * where ... $field >= $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_gte('foo', 20)->get('foobar');
   *
   */
  public function where_gte($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$gte'] = $x;
    return($this);
  }
  /**
   * where ... $field < $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_lt('foo', 20)->get('foobar');
   *
   */
  public function where_lt($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$lt'] = $x;
    return($this);
  }
  /**
   * where ... $field <= $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_lte('foo', 20)->get('foobar');
   *
   */
  public function where_lte($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$lte'] = $x;
    return($this);
  }
  /**
   * where ... $field >= $x AND $field <= $y .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_between('foo', 20, 30)->get('foobar');
   *
   */
  public function where_between($field = '', $x, $y) {
    $this->where_init($field);
    $this->wheres[$field]['$gte'] = $x;
    $this->wheres[$field]['$lte'] = $y;
    return($this);
  }
  /**
   * where ... $field > $x AND $field < $y .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_between_ne('foo', 20, 30)->get('foobar');
   *
   */
  public function where_between_ne($field = '', $x, $y) {
    $this->where_init($field);
    $this->wheres[$field]['$gt'] = $x;
    $this->wheres[$field]['$lt'] = $y;
    return($this);
  }
  /**
   * where ... $field <> $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_ne('foo', 20)->get('foobar');
   *
   */
  public function where_ne($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$ne'] = $x;
    return($this);
  }
  /**
   * where ... or .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_or('foo', array('foo', 'bar'))->get('foobar');
   *
   */
  public function where_or($field = '', $values) {
    $this->where_init($field);
    $this->wheres[$field]['$or'] = $values;
    return($this);
  }
  /**
   *  where ... and .. 条件查询判断
   *  
   *  @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' );
   */
   public function where_and( $elements_values = array() ) {
     foreach ( $elements_values as $element => $val ) {
       $this->wheres[$element] = $val;
     }
     return($this);
   }
  /**
   *  where $field % $num = $result
   *
   *  @usage = $this->mongo_db->where_mod( 'foo', 10, 1 );
   */   
   public function where_mod( $field, $num, $result ) {
     $this->where_init($field);
     $this->wheres[$field]['$mod'] = array($num, $result);
     return($this);
   }
  /**
   * where size
   *
   *  Get the documents where the size of a field is in a given $size int
   *
   *  @usage : $this->mongo_db->where_size('foo', 1)->get('foobar');
   */
  public function where_size($field = "", $size = "") {
    $this->where_init($field);
    $this->wheres[$field]['$size'] = $size;
    return ($this);
  }
  /**
   * like条件查询(PHP中定义MongoRegex类实现)
   *
   * @usage : $this->mongo_db->like('foo', 'bar', 'im', false, false)->get();
   */
  public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = true, $enable_end_wildcard = true) {
    $field = (string)$field;
    $this->where_init($field);
    $value = (string)$value;
    $value = quotmeta($value);
    
    if (true !== $enable_start_wildcard) {
      $value = "^".$value;
    }
    
    if (true !== $enable_end_wildcard) {
      $value .= "$";
    }
    
    $regex = "/$value/$flags";
    $this->wheres[$field] = new MongoRegex($regex);
    return($this);
  }
  /**
   * order排序( 1 => ASC, -1 => DESC)
   *
   * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->order_by(array("age" => 1));
   */
  public function order_by($fields = array()) {
    foreach($fields as $col => $val) {
      if ($val == -1 || $val == false || strtolower($val) == "desc") {
        $this->sorts[$col] = -1;
      } else {
        $this->sorts[$col] = 1;
      }
    }
    return($this);
  }
  /**
   * limit
   *
   * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->limit(10);
   */
  public function limit($x = 999999) {
    if ($x !== NULL && is_numeric($x) && $x >= 1) {
      $this->limit = (int)$x;
    }
    return($this);
  }
  /**
   * offset
   *
   * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->offset(10);
   */
  public function offset($x = 0) {
     if($x !== NULL && is_numeric($x) && $x >= 1) {
       $this->offset = (int) $x;
     }
     return($this);
  }
  /**
   * get_where
   * 
   * @usage: $this->mongo_db->get_where('foo', array('bar' => 'something'));
   */
  public function get_where($collection = "", $where = array(), $limit = 999999) {
    return($this->where($where)->limit($limit)->get($collection));
  }
  /**
   * get
   *
   * @usage: $this->mongo_db->where(array('name' => 'tom'))->get('foo');
   */
  public function get($collection) {
    if (empty($collection)) {
      $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed");
      exit;
    }
    $results = array();
    $results = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts);
    $returns = array();
    foreach($results as $result) {
      $returns[] = $result;
    }
    $this->clear();
    return($returns);
  }
  /**
   * count
   *
   * @usage: $this->db->get_where('foo', array('name' => 'tom'))->count('foo'); 
   */
  public function count($collection) {
    if (empty($collection)) {
      $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed");
      exit;
    }
    $count = $this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count();
    $this->clear();
    return($count);
  }
  /**
   * insert
   *
   * @usage: $this->mongo_db->insert('foo', array('name' => 'tom'));
   */
  public function insert($collection = "", $data = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    if (count($data) == 0 || ! is_array($data)) {
      $this->log_error("Nothing to insert into Mongo collection or insert is not an array");
      exit;
    }
    try {
      $this->db->{$collection}->insert($data, array('fsync' => true));
      if (isset($data['_id'])) {
        return($data['_id']);
      } else {
        return(false);
      }
    } catch(MongoCursorException $e) {
      $this->log_error("Insert of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * update : 利用MongoDB的 $set 实现
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->update('foo', array('age' => 24))
   */
  public function update($collection = "", $data = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    if (count($data) == 0 || ! is_array($data)) {
      $this->log_error("Nothing to update in Mongo collection or update is not an array");
      exit;
    }
    try {
      $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => false)); //注意: multiple为false
      return(true);
    } catch(MongoCursorException $e) {
      $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * update_all : 利用MongoDB的 $set 实现
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->update_all('foo', array('age' => 24));
   */
  public function update_all($collection = "", $data = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    if (count($data) == 0 || ! is_array($data)) {
      $this->log_error("Nothing to update in Mongo collection or update is not an array");
      exit;
    }
    try {
      $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => true)); //注意: multiple为true
      return(true);
    } catch(MongoCursorException $e) {
      $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * delete 
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete('foo');
   */
  public function delete($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    try {
      $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => true)); //注意justOne为true;
    } catch(MongoCursorException $e) {
      $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }  
  /**
   * delete_all
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete_all('foo');
   */
  public function delete_all($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    try {
      $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => false)); //注意justOne为false;
    } catch(MongoCursorException $e) {
      $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /** 
   * add_index
   *
   * @usage : $this->mongo_db->add_index('foo', array('first_name' => 'ASC', 'last_name' => -1), array('unique' => true)));
   */
  public function add_index($collection, $keys = array(), $options = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    if (empty($keys) || ! is_array($keys)) {
      $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
      exit;
    }
    foreach($keys as $col => $val) {
      if ($val == -1 || $val == false || strtolower($val) == 'desc') {
        $keys[$col] = -1;
      } else {
        $keys[$col] = 1;
      }
    }
    //在此没有对$options数组的有效性进行验证
    if (true == $this->db->{$collection}->ensureIndex($keys, $options)) {
      $this->clear();
      return($this);
    } else {
      $this->log_error("An error occured when trying to add an index to MongoDB Collection");
      exit;
    }
  }
  /**
   * remove_index
   *
   * @usage : $this->mongo_db->remove_index('foo', array('first_name' => 'ASC', 'last_name' => -1))
   */
  public function remove_index($collection = "", $keys = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    if (empty($keys) || ! is_array($keys)) {
      $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
      exit;
    }
    if ($this->db->{$collection}->deleteIndex($keys)) {
      $this->clear();
      return($this);
    } else {
      $this->log_error("An error occured when trying to add an index to MongoDB Collection");
      exit;
    }
  }
  /**
   * remove_all_index
   *
   * @usage : $this->mongo_db->remove_all_index('foo', array('first_name' => 'ASC', 'last_name' => -1))
   */
  public function remove_all_index($collection = "", $keys = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    if (empty($keys) || ! is_array($keys)) {
      $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
      exit;
    }
    if ($this->db->{$collection}->deleteIndexes($keys)) {
      $this->clear();
      return($this);
    } else {
      $this->log_error("An error occured when trying to add an index to MongoDB Collection");
      exit;
    }
  }
  /**
   * list_indexes
   *
   * @usage : $this->mongo_db->list_indexes('foo');
   */
  public function list_indexes($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    return($this->db->{$collection}->getIndexInfo());
  }
  /**
   * drop_collection
   *
   * @usage : $this->mongo_db->drop_collection('foo');
   */
  public function drop_collection($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    $this->db->{$collection}->drop();
    return(true);
  }
  /**
   * 生成连接MongoDB 参数字符串
   *
   */
  private function connection_string() {
    include_once($this->mongo_config);
    $this->host = trim($config['host']);
    $this->port = trim($config['port']);
    $this->user = trim($config['user']);
    $this->pass = trim($config['pass']);
    $this->dbname = trim($config['dbname']);
    $this->persist = trim($config['persist']);
    $this->persist_key = trim($config['persist_key']);
    $connection_string = "mongodb://";
    if (empty($this->host)) {
      $this->log_error("The Host must be set to connect to MongoDB");
      exit;
    }
    if (empty($this->dbname)) {
      $this->log_error("The Database must be set to connect to MongoDB");
      exit;
    }
    if ( ! empty($this->user) && ! empty($this->pass)) {
      $connection_string .= "{$this->user}:{$this->pass}@";
    }
    if ( isset($this->port) && ! empty($this->port)) {
      $connection_string .= "{$this->host}:{$this->port}";
    } else {
      $connection_string .= "{$this->host}";
    }
    $this->connection_string = trim($connection_string);
  }
  /**
   * 连接MongoDB 获取数据库操作句柄
   *
   */
  private function connect() {
    $options = array();
    if (true === $this->persist) {
      $options['persist'] = isset($this->persist_key) && ! empty($this->persist_key)  $this->persist_key : "ci_mongo_persist";
    }
    try {
      $this->connection = new Mongo($this->connection_string, $options);
      $this->db = $this->connection->{$this->dbname};
      return ($this);
    } catch (MongoConnectionException $e) {
      $this->log_error("Unable to connect to MongoDB: {$e->getMessage()}");
    }
  }
  /**
   * 初始化清理部分成员变量
   * 
   */
  private function clear() {
    $this->selects = array();
    $this->wheres = array();
    $this->limit = NULL;
    $this->offset = NULL;
    $this->sorts = array();
  }
  /**
   * 依据字段名初始化处理$wheres数组
   *
   */
  private function where_init($param) {
    if ( ! isset($this->wheres[$param])) {
      $this->wheres[$param] = array();
    }
  }
  /**
   * 错误记录
   *
   */
  private function log_error($msg) {
    $msg = "[Date: ".date("Y-m-i H:i:s")."] ".$msg;
    @file_put_contents("./error.log", print_r($msg."\n", true), FILE_APPEND);
  }
}
/* End of MyMongo.php */

2. mongo_config.php配置文件:

<php
$config["host"] = "localhost";
$config["user"] = "";
$config["pass"] = "";
$config["port"] = 27017;
$config["dbname"] = "test";
$config['persist'] = TRUE;
$config['persist_key'] = 'ci_mongo_persist';
/*End of mongo_config.php*/

3. MyMongoDemo.php文件:

<php
include_once("MyMongo.php");
$conn = new MyMongo();
//删除所有记录
$conn->delete_all("blog");
//插入第一条记录
$value = array("name" => "小明", "age" => 25, "addr" => array("country" => "中国", "province" => "广西", "city" => "桂林"));
$conn->insert("blog", $value);
var_dump($conn->select(array("name", "age"))->get("blog"));
var_dump($conn->get("blog"));
/* End of MyMongoDemo.php */

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

 
标签: php MongoDB
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • php-fpm进程管理的三种模式 phpfpm子进程
    php-fpm进程管理的三种模式 phpfpm子进程
    php-fpm解读-进程管理的三种模式—程序媛大丽标明转载以示尊重 感谢原作者的分享。php-fpm进程管理一共有三种模式:ondemand、static、dynamic,我们可以在同一个fpm的master配置三种模式,看下图1。php-fpm的工作模式和nginx类似,都是一个master,多个worke
    03-08
  • nginx和php-fpm 是使用 tcp socket 还是 unix s
    tcp socket允许通过网络进程之间的通信,也可以通过loopback进行本地进程之间通信。unix socket允许在本地运行的进程之间进行通信。分析从上面的图片可以看,unix socket减少了不必要的tcp开销,而tcp需要经过loopback,还要申请临时端口和tcp相关资源。但是
    03-08
  • [PHP8] 我参加了PHP8工程师认证初学者考试beta考试
    [PHP8] 我参加了PHP8工程师认证初学者考试beta
    前几天,2022/08/05,PHP工程师认证机构PHP8 技术员认证初级考试宣布实施考试将于 2023 年春季开始。和 beta 测试完成于 2022/09/11所以我收到了。一般社团法人BOSS-CON JAPAN(代表理事:Tadashi Yoshimasa,地点:东京都世田谷区,以下简称“BOSS-CON JAPAN
    03-08
  • 将 PHP Insights 放入旧版 PJ 不是很好吗?谈论
    将 PHP Insights 放入旧版 PJ 不是很好吗?谈论
    介绍在最近的PHP系统开发中,感觉故事在理所当然包含静态分析工具的前提下进行。我的周围现有代码很脏,我很久以前安装了工具,但几乎没有检查已经观察到许多这样的案例。 (这是小说。而不是像 0 或 100 这样不允许单行错误的静态分析,一点一点,逐渐我想介
    03-08
  • PHP基于elasticsearch全文搜索引擎的开发 php使
    1.概述:全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选。Elastic 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接
    02-09
  • php视图操作
    一、视图的基本介绍         视图是虚拟的表。与包含数据的表不一样,视图只包含使用时动态检索数据的查询。        使用视图需要MySQL5及以后的版本支持。        下面是视图的一些常见应用:        重用SQL语句;        简化复杂的S
    02-09
  • php中图像处理的常用函数 php图形图像处理技术
    php中图像处理的常用函数 php图形图像处理技术
    1.imagecreate()函数imagecreate()函数是基于一个调色板的画布。?php $im = imagecreate(200,80);                //创建一个宽200,高80的画布。$white = imagecolorallocate($im,225,35,180);     //设置画布的背景颜色imagegif($im);
    02-09
  • PHP安全之webshell和后门检测
    PHP安全之webshell和后门检测
    基于PHP的应用面临着各种各样的攻击:XSS:对PHP的Web应用而言,跨站脚本是一个易受攻击的点。攻击者可以利用它盗取用户信息。你可以配置Apache,或是写更安全的PHP代码(验证所有用户输入)来防范XSS攻击SQL注入:这是PHP应用中,数据库层的易受攻击点。防范
    02-09
  • php使用时间戳保存时间的意义 PHP获取时间戳
    时间戳记录的是格林尼治时间,使用date格式化的时候会根据你程序设置的不同时区显示不同的时间。如果使用具体时间,则还需要进行多一步转换。
    02-09
  • PHP 获取提交表单数据方法
    PHP $_GET 和 $_POST变量是用来获取表单中的信息的,比如用户输入的信息。PHP表单操作在我们处理HTML表单和PHP表单时,我们要记住的重要一点是:HTML页面中的任何一个表单元素都可以自动的用于PHP脚本:表单举例: htmlbodyform action="welcome.php" method
    02-09
点击排行