MongoDB single-instance mode operation class implemented by php, mongodb implemented by php
This article describes the mongoDB single-instance mode operation class implemented by php. We will share this with you for your reference. The details are as follows:
Reading a lot of mongo classes is not satisfactory. Finally, we found that classes do not need to be encapsulated by ourselves. The built-in methods of php mongo extension are very convenient.
However, it is customary to encapsulate the database connection part. Finally, I encapsulated a single-instance database class.
The Singleton mode is used to avoid wasting resources by generating multiple instances.
The following is the encapsulated code.
Class Mongo_db {private static $ cli;/*** initialization not allowed */private function _ construct () {$ config = Config: get ('config. pai_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 guest client ($ 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, and mycollection is the selected table. Because the singleton mode is used, you can refer to the following article for more information about how to operate only one resource.
Here is an article about how php operates mongo in detail and easy to understand. I hope you can refer
Http://www.bkjia.com/article/37727.htm