This article explains how PHP implements the MongoDB Singleton mode operation class.
See a lot of MONGO class are unsatisfactory. Finally, we found that we didn't need to encapsulate the class. The PHP MONGO extension comes in handy.
But it is customary to encapsulate the database connection. Finally, I encapsulated a database class for a singleton pattern
Singleton mode is used to avoid generating multiple instances, wasting resources
The following is the encapsulated code
Class Mongo_db{private static $cli;/** * does not allow initialization of */Private function __construct () {$config = Config::get (' Config.mongo_c Onfig '); if (empty ($config)) {$this->throwerror (' Cannot 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 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
This article explains how PHP implements the MongoDB Singleton mode operation class, more relevant content please pay attention to the PHP Chinese web.