PHP Encapsulated Simple Connection MongoDB Class Sample

  • 2021-11-24 01:10:24
  • OfStack

This article illustrates the simple connection MongoDB class encapsulated by PHP. Share it for your reference, as follows:

1. Encapsulate the MongoDB class


<?php
class MongoDB
{
  private $database;
  private $mongo;
  function __construct()
   {
    $this->mongo = new MongoClient("mongodb://user:password@server_address:port/admin");
    $this->database = $this->mongo->selectDB("data");
  }
  {
    return $this->database->selectCollection($collection);
  }
  // Gets all collection names 
  function getCollections() 
  {
    return $this->database->getCollectionNames();
  }
  // Select database 
  function selectDB($db)
  {
    $this->database = $this->mongo->selectDB($db);
  }
}

2. Simple call, insert data.


class DemoController extends CI_Controller
{
  function __construct() {
    parent::__construct();
    //CI Load classes in 
    $this->load->library('mongo_lib', '', 'mongodb');
  }
  // Insert 1 Bar data 
  function create()
  {
    $data = array('name'=>'mike','email'=>'abc@163.com);
    // Select the library, shell : user demo_db
    $this->mongodb->selectDB('demo_db');
    // Selection set ,db.demo_col.insert();
    $rebateCollection = $this->mongodb->getCollection('demo_collection');
    $res = $rebateCollection->insert($data);
  }
}

For more readers interested in PHP related contents, please check the topics of this site: "PHP+MongoDB database operation skills", "PHP database operation skills summary based on pdo", "php object-oriented programming introduction tutorial", "php string (string) usage summary", "php+mysql database operation introduction tutorial" and "php common database operation skills summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: