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
classmongo_db{Private Static $cli; /** * Not allowed to initialize*/ Private function__construct () {$config= Config::get (' Config.mongo_config '); if(Empty($config)){ $this->throwerror (' Unable to connect to database! ‘); } if(!Empty($config["User_name"])) { $this->mongo =NewMongoclient ("mongodb://{$config[' User_name ']}:{$config[' Password ']} @{$config[' Host ']}:{$config[' Port ']} '); }Else { $this->mongo =NewMongoclient ($config[' Host ']. ‘:‘ .$config[' Port ']); } } /** * single case mode * @return Mongo|null*/ Public Static functionCLI () {if(! (Self::$cliinstanceof Self)) { Self::$cli=NewSelf (); } returnSelf::$cli-MONGO; }}
$mongo = MONGO_DB::CLI ()->test->mycollection; Test is the selected database, MyCollection is the selected table. Because singleton mode is used, only one resource is instantiated
Please refer to the following article for specific operation
Here is an article about PHP on the operation of the MONGO, very detailed, but also very easy to understand. I hope you see the following
Http://www.cnblogs.com/jackluo/archive/2013/06/16/3138835.html
PHP MONGO Class