首頁 > 後端開發 > php教程 > php操作MongoDB類別範例程式碼

php操作MongoDB類別範例程式碼

怪我咯
發布: 2023-03-13 07:40:02
原創
1607 人瀏覽過

這篇文章主要介紹了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(&#39;Mongo&#39;)) {
      $this->log_error("The MongoDB PECL extentiosn has not been installed or enabled.");
      exit;
    }
    
    $this->connection_string();
    $this->connect();
  }
  /**
   * 更改数据库
   *
   */
  public function switch_db($database = &#39;&#39;) {
    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(&#39;foo&#39; => &#39;bar&#39;))->get(&#39;foobar&#39;);
   *
   */
  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(&#39;foo&#39;, array(&#39;bar&#39;, &#39;zoo&#39;))->get(&#39;foobar&#39;);
   *
   */
  public function where_in($field = &#39;&#39;, $in = array()) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$in&#39;] = $in;
    return($this);
  }
  /**
   * where ... not in .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_not_in(&#39;foo&#39;, array(&#39;bar&#39;, &#39;zoo&#39;))->get(&#39;foobar&#39;);
   *
   */
  public function where_not_in($field = &#39;&#39;, $in = array()) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$nin&#39;] = $in;
    return($this);
  }
  /**
   * where ... $field > $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_gt(&#39;foo&#39;, 20)->get(&#39;foobar&#39;);
   *
   */
  public function where_gt($field = &#39;&#39;, $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gt&#39;] = $x;
    return($this);
  }
  /**
   * where ... $field >= $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_gte(&#39;foo&#39;, 20)->get(&#39;foobar&#39;);
   *
   */
  public function where_gte($field = &#39;&#39;, $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gte&#39;] = $x;
    return($this);
  }
  /**
   * where ... $field < $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_lt(&#39;foo&#39;, 20)->get(&#39;foobar&#39;);
   *
   */
  public function where_lt($field = &#39;&#39;, $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$lt&#39;] = $x;
    return($this);
  }
  /**
   * where ... $field <= $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_lte(&#39;foo&#39;, 20)->get(&#39;foobar&#39;);
   *
   */
  public function where_lte($field = &#39;&#39;, $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$lte&#39;] = $x;
    return($this);
  }
  /**
   * where ... $field >= $x AND $field <= $y .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_between(&#39;foo&#39;, 20, 30)->get(&#39;foobar&#39;);
   *
   */
  public function where_between($field = &#39;&#39;, $x, $y) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gte&#39;] = $x;
    $this->wheres[$field][&#39;$lte&#39;] = $y;
    return($this);
  }
  /**
   * where ... $field > $x AND $field < $y .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_between_ne(&#39;foo&#39;, 20, 30)->get(&#39;foobar&#39;);
   *
   */
  public function where_between_ne($field = &#39;&#39;, $x, $y) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gt&#39;] = $x;
    $this->wheres[$field][&#39;$lt&#39;] = $y;
    return($this);
  }
  /**
   * where ... $field <> $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_ne(&#39;foo&#39;, 20)->get(&#39;foobar&#39;);
   *
   */
  public function where_ne($field = &#39;&#39;, $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$ne&#39;] = $x;
    return($this);
  }
  /**
   * where ... or .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_or(&#39;foo&#39;, array(&#39;foo&#39;, &#39;bar&#39;))->get(&#39;foobar&#39;);
   *
   */
  public function where_or($field = &#39;&#39;, $values) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$or&#39;] = $values;
    return($this);
  }
  /**
   *  where ... and .. 条件查询判断
   *  
   *  @usage = $this->mongo_db->where_and( array ( &#39;foo&#39; => 1, &#39;b&#39; => &#39;someexample&#39; );
   */
   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( &#39;foo&#39;, 10, 1 );
   */   
   public function where_mod( $field, $num, $result ) {
     $this->where_init($field);
     $this->wheres[$field][&#39;$mod&#39;] = 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(&#39;foo&#39;, 1)->get(&#39;foobar&#39;);
   */
  public function where_size($field = "", $size = "") {
    $this->where_init($field);
    $this->wheres[$field][&#39;$size&#39;] = $size;
    return ($this);
  }
  /**
   * like条件查询(PHP中定义MongoRegex类实现)
   *
   * @usage : $this->mongo_db->like(&#39;foo&#39;, &#39;bar&#39;, &#39;im&#39;, 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(&#39;foo&#39;, array(&#39;name&#39; => &#39;tom&#39;))->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(&#39;foo&#39;, array(&#39;name&#39; => &#39;tom&#39;))->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(&#39;foo&#39;, array(&#39;name&#39; => &#39;tom&#39;))->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(&#39;foo&#39;, array(&#39;bar&#39; => &#39;something&#39;));
   */
  public function get_where($collection = "", $where = array(), $limit = 999999) {
    return($this->where($where)->limit($limit)->get($collection));
  }
  /**
   * get
   *
   * @usage: $this->mongo_db->where(array(&#39;name&#39; => &#39;tom&#39;))->get(&#39;foo&#39;);
   */
  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(&#39;foo&#39;, array(&#39;name&#39; => &#39;tom&#39;))->count(&#39;foo&#39;); 
   */
  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(&#39;foo&#39;, array(&#39;name&#39; => &#39;tom&#39;));
   */
  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(&#39;fsync&#39; => true));
      if (isset($data[&#39;_id&#39;])) {
        return($data[&#39;_id&#39;]);
      } 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(&#39;name&#39; => &#39;tom&#39;))->update(&#39;foo&#39;, array(&#39;age&#39; => 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(&#39;$set&#39; => $data), array(&#39;fsync&#39; => true, &#39;multiple&#39; => 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(&#39;name&#39; => &#39;tom&#39;))->update_all(&#39;foo&#39;, array(&#39;age&#39; => 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(&#39;$set&#39; => $data), array(&#39;fsync&#39; => true, &#39;multiple&#39; => 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(&#39;name&#39; => &#39;tom&#39;))->delete(&#39;foo&#39;);
   */
  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(&#39;fsync&#39; => true, &#39;justOne&#39; => 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(&#39;name&#39; => &#39;tom&#39;))->delete_all(&#39;foo&#39;);
   */
  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(&#39;fsync&#39; => true, &#39;justOne&#39; => 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(&#39;foo&#39;, array(&#39;first_name&#39; => &#39;ASC&#39;, &#39;last_name&#39; => -1), array(&#39;unique&#39; => 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) == &#39;desc&#39;) {
        $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(&#39;foo&#39;, array(&#39;first_name&#39; => &#39;ASC&#39;, &#39;last_name&#39; => -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(&#39;foo&#39;, array(&#39;first_name&#39; => &#39;ASC&#39;, &#39;last_name&#39; => -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(&#39;foo&#39;);
   */
  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(&#39;foo&#39;);
   */
  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[&#39;host&#39;]);
    $this->port = trim($config[&#39;port&#39;]);
    $this->user = trim($config[&#39;user&#39;]);
    $this->pass = trim($config[&#39;pass&#39;]);
    $this->dbname = trim($config[&#39;dbname&#39;]);
    $this->persist = trim($config[&#39;persist&#39;]);
    $this->persist_key = trim($config[&#39;persist_key&#39;]);
    $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[&#39;persist&#39;] = 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[&#39;persist&#39;] = TRUE;
$config[&#39;persist_key&#39;] = &#39;ci_mongo_persist&#39;;
/*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操作MongoDB類別範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板