mongoDB singleton mode operation class implemented by php

  • 2021-08-31 07:32:41
  • OfStack

In this paper, an example is given to describe the mongoDB singleton mode operation class implemented by php. Share it for your reference, as follows:

After reading a lot of mongo classes, they are not satisfactory. Finally, I found that I don't need to wrap the class myself at all. The extension of php and mongo comes with its own method, which is very convenient

But it is customary to encapsulate the database connection part. Finally, I encapsulated a singleton database class

The singleton pattern is used to avoid generating multiple instances and wasting resources

Here 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(' Unable to connect to 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 pattern 
  * @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 selected database   ,  mycollection  Is the selected table.   Because singleton mode is used, only instances of 1 Refer to the following article for specific operation of resources 

Here is a 1 article, php to mongo operation, very detailed, also very easy to understand. I hope you can refer to it
https://www.ofstack.com/article/37727.htm

For more readers interested in PHP related contents, please check the topics of this site: "PHP+MongoDB Database Operation Skills Encyclopedia", "PHP Database Operation Skills Summary Based on pdo", "php Object-Oriented Programming Introduction Course", "php String (string) Usage Summary", "php+mysql Database Operation Introduction Course" and "php Common Database Operation Skills Summary"

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


Related articles: