MongoDB database operation class sharing _php instance of PHP implementation

Source: Internet
Author: User
Tags create index findone getmessage mongodb mongodb server rand
Class Hmongodb {private $mongo;
  MongoDB connection 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 $m
    ongodb_arr[$flag [' tag ']];
      else {$mongo = new Hmongodb ($mongo _server);
      $mongodb _arr[$flag [' tag ']] = $mongo;
    return $mongo; }/** * constructor * supports incoming multiple mongo_server (1. Connect the other server 2 when a problem occurs. Automatically distribute queries evenly to different servers) * Parameters: * $mongo _server: Array or String-array ("127.0.0.1:1111", "127.0.0.1:2222")-"127.0.0.1:1111 "* $connect: Whether to initialize the MONGO object when connected, the default connection * $auto _balance: Whether automatic load balancing, the default is * * return value: * Success: MONGO Object * failed: Fals E/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 _ser
    ver[$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;
    }/** * Connection MongoDB Server * * Parameters: No * * return Value: * Success: TRUE * failed: false/Public Function connect () {
      try {$this->mongo->connect ();
    return true;
      The catch (Mongoconnectionexception $e) {$this->error = $e->getmessage ();
    return false; }/** * Select DB * * Parameters: $dbname * * return value: no */Public function Selectdb ($dbname) {$this->
  Curr_db_name = $dbname;
  /** * CREATE INDEX: If index already exists, return. * * Parameters: * $table _name: Table name * $index: Index-array ("id" =>1)-establish ascending index in ID field * $index _param: Other conditions-Unique index etc * Return value: * Successful : True * Failed: false */Public function ensureindex ($table _name, $index, $index _param=array ()) {$dbname = $this-&
    Gt;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; /** * Insert Record * * Parameters: * $table _name: Table name * $record: Record * * return value: * Success: TRUE * failed: false/Public Fu
    Nction Insert ($table _name, $record) {$dbname = $this->curr_db_name;
      try {$this->mongo-> $dbname-> $table _name->insert ($record, Array (' safe ' =>true));
    return true;
      The catch (Mongocursorexception $e) {$this->error = $e->getmessage ();
    return false; 
    /** * Query table number of records * * Parameters: * $table _name: Table name * * Return value: Table number of records/Public function count ($table _name) {
    $dbname = $this->curr_db_name;
  return $this->mongo-> $dbname-> $table _name->count (); /** * Update Record * * Parameters: * $table _name: Table name * $condition: Update condition * $newdata: New data record * $options: Update selection-upsert/multi PLE * * Return value: * Successful: TRUE * failed: 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;
      The catch (Mongocursorexception $e) {$this->error = $e->getmessage ();
    return false; }/** * Delete record * * Parameters: * $table _name: Table name * $condition: Delete condition * $options: Delete selection-justone * * return Value: * Success: True * Failed: false */Public function remove ($table _name, $condition, $options =array ()) {$dbname = $this->cur
    R_db_name;
    $options [' safe '] = 1;
      try {$this->mongo-> $dbname-> $table _name->remove ($condition, $options);
    return true;
      The catch (Mongocursorexception $e) {$this->error = $e->getmessage ();
  return false; /** * Find Records * * Parameters: * $table _name: Table name * $query _condition: Field Lookup criteria * $result _condition: Query Result Restrictions-limit/so RT etc * $fields: Get field * * return value: * Success: Recordset * failed: false/Public Function find ($table _name, $query _condition, $result _condition=ar
    Ray (), $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 ();
      The catch (Mongoconnectionexception $e) {$this->error = $e->getmessage ();
    return false;
      The catch (Mongocursortimeoutexception $e) {$this->error = $e->getmessage ();
    return false;
  return $result; }   

  /** * Find a record * * Parameters: * $table _name: Table name * $condition: Find condition * $fields: Get field * * return value: * Success: A record * failed:
    False */Public function FindOne ($table _name, $condition, $fields =array ()) {$dbname = $this->curr_db_name;
  return $this->mongo-> $dbname-> $table _name->findone ($condition, $fields); 
  /** * Get current error message * * Parameter: NO * * return value: Current error message/Public function GetError () {returns $this->error;
  /*** MongoDB Class * * Examples: * $mongo = new Hmongodb ("127.0.0.1:11223");
  * $mongo->selectdb ("test_db");
  * CREATE INDEX * $mongo->ensureindex ("test_table", Array ("id" =>1), Array (' unique ' =>true));
  * Get the record of the table * $mongo->count ("test_table");
  * Insert Record * $mongo->insert ("test_table", Array ("id" =>2, "title" => "Asdqw"));
  * Update record * $mongo->update ("test_table", Array ("id" =>1), Array ("id" =>1, "title" => "BBB")); * Update records-when they are present and added when they are not present-equivalent to set * $mongo->update ("test_table", Array ("id" =>1), Array ("ID" =&gt1, "title" => "BBB"), Array ("Upsert" =>1)); * Find Records * $mongo->find ("C", Array ("title" => "Asdqw"), Array ("Start" =>2, "Limit" =>2, "Sort" =>array ("id" =
  >1)) * Find a record * $mongo->findone ("$mongo->findone (" TTT ", Array (" id "=>1))", Array ("id" =>1));
  * Delete Record * $mongo->remove ("TTT", Array ("title" => "BBB"));
  * Delete Only one record * $mongo->remove ("TTT", Array ("title" => "BBB"), Array ("Justone" =>1));
  * Get the error message for the MONGO operation * $mongo->geterror (); */

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.