SoFunction
Updated on 2025-03-09

MongoDB singleton mode operation class implemented by php

This article describes the mongoDB singleton mode operation class implemented by php. Share it for your reference, as follows:

I have seen many mongo classes but are not satisfactory. Finally, I found that I didn't need to encapsulate the class myself. The method of extending php mongo is already very convenient

But habitually encapsulate the database connection part. Finally, I encapsulate a singleton pattern database class

Use singleton pattern to avoid generating multiple instances and wasting resources

Below is the encapsulated code

class Mongo_db
{
  private static $cli;
  /**
    * Initialization is not allowed
    */
  private function __construct()
  {
    $config = Config::get('config.mongo_config');
    if(empty($config)){
      $this->throwError('Cannot connect to the database!  ');
    }
    if (!empty($config["user_name"])) {
      $this->mongo = new MongoClient("mongodb://{$config['user_name']}:{$config['password']}@{$config['host']}:{$config['port']}");
    }else {
      $this->mongo = new MongoClient($config['host'] . ':' . $config['port']);
    }
  }
  /**
   * Singleton mode
   * @return Mongo|null
   */
 public static function cli(){
  if(!(self::$cli instanceof self)){
   self::$cli = new self();
  }
  return self::$cli->mongo;
 }
}
$mongo = Mongo_db::cli()->test->mycollection; // test is the database of choice , mycollection is the selected table。 Because singleton mode is used,so,Please refer to the following articles if you can only use a resource for specific operations.

Here is an article about php's operation on mongo, which is very detailed and easy to understand. Hope you refer to it
https:///article/

For more information about PHP related content, please check out the topic of this site:Complete collection of PHP+MongoDB database operation skills》、《Summary of PHP's skills to operate database based on pdo》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.