This time to bring you a PHP implementation of the MongoDB single-mode operation of the steps in detail, PHP implementation of the MongoDB single-mode operation of the note what, the following is the actual case, a look.
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_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 selected database, MyCollection is the selected table. Because you use singleton mode, you can only instantiate a resource and then refer to the following article for specific operations
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP implementation of statistics in binary 1 number of algorithm steps in detail
ci Framework (CodeIgniter) Operations Redis Step resolution