Home > Backend Development > PHP Tutorial > Sharing of instance operations of mongoDB singleton mode implemented in PHP

Sharing of instance operations of mongoDB singleton mode implemented in PHP

小云云
Release: 2023-03-19 15:38:02
Original
1736 people have browsed it

This article mainly introduces the mongoDB singleton mode operation class implemented by PHP. It 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 who need it can refer to it. I hope it can help everyone. .

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 是选择的表。 因为使用单例模式,所以,只会实例一个资源具体操作再参考下面的文章吧
Copy after login

Related recommendations:

Detailed explanation of how php7 implements MongoDB fuzzy query

php method to implement singleton mode

The difference between factory mode and singleton mode in php design mode

The above is the detailed content of Sharing of instance operations of mongoDB singleton mode implemented in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template