Home  >  Article  >  Backend Development  >  Relevant explanation of mongoDB singleton mode operation class implemented by PHP

Relevant explanation of mongoDB singleton mode operation class implemented by PHP

jacklove
jackloveOriginal
2018-06-29 18:04:211377browse

This article mainly introduces the mongoDB singleton mode operation class implemented by PHP, and analyzes the related implementation skills of the database encapsulation class of PHP based on the singleton mode to operate the MongoDB database in the form of examples. Friends in need can refer to it

The example of this article describes the mongoDB singleton mode operation class implemented by PHP. I share it with you for your reference. The details are as follows:

I have seen many mongo classes and they are all unsatisfactory. Finally, I found that there was no need to encapsulate the class myself. The methods that come with the php mongo extension are already very convenient

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

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

The following is the encapsulated code

class Mongo_db
{
  private static $cli;
  /**
   * 不允许初始化
   */
  private function __construct()
  {
    $config = Config::get('config.mongo_config');
    if(empty($config)){
      $this->throwError('无法连接数据库!');
    }
    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']);
    }
  }
  /**
  * 单例模式
  * @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 是选择的数据库 , mycollection 是选择的表。 因为使用单例模式,所以,只会实例一个资源具体操作再参考下面的文章吧

Here is an article about the operation of php on mongo, which is very detailed and easy to understand. I hope you can refer to
//www.jb51.net/article/37727.htm

Articles you may be interested in:

tp5( thinkPHP5) Detailed explanation of the method of operating the mongoDB database

Explanation of the solution to PHP Class SoapClient not found

PHP Class SoapClient Solution to not found

The above is the detailed content of Relevant explanation of mongoDB singleton mode operation class implemented by PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn