PHP implementation of the MongoDB action class

Source: Internet
Author: User
Tags foreach count manual findone getmessage mongoclient mongodb


Speaking of PHP even MongoDB, had to first introduce the official PHP manual, Web site in: http://us.php.net/manual/en/ book.mongo.php, next to share a I commonly used MongoDB operation class, see the database operations have, small partners can refer to.



mongo_db.php




<? php
  
/ **
 * Created by PhpStorm.
 * User: yangyulong
 * Date: 5/26/2015
 * Time: 13:45
 * /
class Mongo_db
{
  private static $ instanceof = NULL;
  public $ mongo;
  private $ host = 'localhost';
  private $ port = '27017';
  
  private $ db;
  public $ dbname;
  private $ table = NULL;
  
  / **
   * Initialize the class and get the mongo instance object
   * /
  public function __construct ($ host = NULL, $ port = NULL, $ dbname = NULL, $ table = NULL)
  {
  
    if (NULL === $ dbname) {
      $ this-> throwError ('Collection cannot be empty!');
    }
  
    // determine whether host and port are passed
    if (NULL! == $ host) {
      $ this-> host = $ host;
    }
  
    if (NULL! == $ port) {
      $ this-> port = $ port;
    }
  
    $ this-> table = $ table;
  
    $ this-> mongo = new MongoClient ($ this-> host. ':'. $ this-> port);
    if ($ this-> getVersion ()> = '0.9.0') {
      $ this-> dbname = $ this-> mongo-> selectDB ($ dbname);
      $ this-> db = $ this-> dbname-> selectCollection ($ table);
    } else {
      $ this-> db = $ this-> mongo-> $ dbname-> $ table;
    }
  }
  
  public function getVersion ()
  {
    return MongoClient :: VERSION;
  }
  
  / **
   * Singleton mode
   * @return Mongo | null
   * /
  // public static function getInstance ($ host = null, $ port = null, $ dbname = null, $ table = null) {
  //
  // if (! (self :: $ instanceof instanceof self)) {
  // self :: $ instanceof = new self ($ host, $ port, $ dbname, $ table);
  //}
  //
  // return self :: $ instanceof;
  //}
  
  / **
   * Insert a piece of data
   * @param array $ doc
   * /
  public function insert ($ doc = array ())
  {
    if (empty ($ doc)) {
      $ this-> throwError ('The inserted data cannot be empty!');
    }
    // Save data information
    try {
      if (! $ this-> db-> insert ($ doc)) {
        throw new MongoException ('Failed to insert data');
      }
    } catch (MongoException $ e) {
      $ this-> throwError ($ e-> getMessage ());
    }
  }
  
  / **
   * Insert multiple data messages
   * @param array $ doc
   * /
  public function insertMulti ($ doc = array ())
  {
    if (empty ($ doc)) {
      $ this-> throwError ('The inserted data cannot be empty!');
    }
    // Insert data information
    foreach ($ doc as $ key => $ val) {
      // Check if $ val is an array
      if (is_array ($ val)) {
        $ this-> insert ($ val);
      }
    }
  }
  
  / **
   * Find a record
   * @return array | null
   * /
  public function findOne ($ where = NULL)
  {
    if (NULL === $ where) {
      try {
        if ($ result = $ this-> db-> findOne ()) {
          return $ result;
        } else {
          throw new MongoException ('Failed to find data');
        }
      } catch (MongoException $ e) {
        $ this-> throwError ($ e-> getMessage ());
      }
    } else {
      try {
        if ($ result = $ this-> db-> findOne ($ where)) {
          return $ result;
        } else {
          throw new MongoException ('Failed to find data');
        }
      } catch (MongoException $ e) {
        $ this-> throwError ($ e-> getMessage ());
      }
    }
  
  }
  
  / **
   * todo followed by condition
   * Find all documents
   * @return MongoCursor
   * /
  public function find ($ where = NULL)
  {
    if (NULL === $ where) {
  
      try {
        if ($ result = $ this-> db-> find ()) {
  
        } else {
          throw new MongoException ('Failed to find data');
        }
      } catch (MongoException $ e) {
        $ this-> throwError ($ e-> getMessage ());
      }
    } else {
      try {
        if ($ result = $ this-> db-> find ($ where)) {
  
        } else {
          throw new MongoException ('Failed to find data');
        }
      } catch (MongoException $ e) {
        $ this-> throwError ($ e-> getMessage ());
      }
    }
  
    $ arr = array ();
    foreach ($ result as $ id => $ val) {
      $ arr [] = $ val;
    }
  
    return $ arr;
  }
  
  / **
   * Get the number of records
   * @return int
   * /
  public function getCount ()
  {
    try {
      if ($ count = $ this-> db-> count ()) {
        return $ count;
      } else {
        throw new MongoException ('Find total failed');
      }
    } catch (MongoException $ e) {
      $ this-> throwError ($ e-> getMessage ());
    }
  }
  
  / **
   * Get all databases
   * @return array
   * /
  public function getDbs ()
  {
    return $ this-> mongo-> listDBs ();
  }
  
  / **
   * Delete database
   * @param null $ dbname
   * @return mixed
   * /
  public function dropDb ($ dbname = NULL)
  {
    if (NULL! == $ dbname) {
      $ retult = $ this-> mongo-> dropDB ($ dbname);
      if ($ retult ['ok']) {
        return TRUE;
      } else {
        return FALSE;
      }
    }
    $ this-> throwError ('Please enter the name of the database to delete');
  }
  
  / **
   * Force close database link
   * /
  public function closeDb ()
  {
    $ this-> mongo-> close (TRUE);
  }
  
  / **
   * Output error message
   * @param $ errorInfo error content
   * /
  public function throwError ($ errorInfo = '')
  {
    echo "<h3> Something went wrong: $ errorInfo </ h3>";
    die ();
  }
  
}



The above is the entire contents of this article, I hope you can enjoy.


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.