MongoDB single-instance mode operation class implemented by php, mongodb implemented by php

Source: Internet
Author: User

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

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.