How PHP implements the MongoDB Singleton mode operation class

Source: Internet
Author: User
Tags mongoclient
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.