PHP Implementation MongoDB Singleton mode operation steps

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

Related Article

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.