php operation mongodb encapsulation class and usage example

  • 2021-11-01 02:33:32
  • OfStack

This article illustrates the php operation mongodb encapsulation class and its usage. Share it for your reference, as follows:

Recently, I learned mongodb, which happened to be developed by php, and wrote the encapsulation class of php operation mongodb casually.


<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2016/10/24
 * Time: 13:49
 */
namespace App\Http\Controllers\Api;
use App\Http\Common\ReturnApi;
/*
 *
 *
 mongdb General operation 
 */
class MongdbCommonController
{
  private static $conn;
  private static $mon;
  private static $error;
  private function __construct(){
    //self::$conn = new \MongoClient("mongodb://".env('MONGDB_USER').":".env('MONGDB_PASS')."@".env('MONGDB_HOST').":".env('MONGDB_PORT')."/".env('MONGDB_DB'));
    self::$conn = new \MongoClient("mongodb://".env('MONGDB_USER').":".env('MONGDB_PASS')."@".env('MONGDB_HOST').":".env('MONGDB_PORT'));
    //self::$conn = new \MongoClient("mongodb://".env('MONGDB_HOST').":".env('MONGDB_PORT'));
    $db = env('MONGDB_DB');
    self::$mon = self::$conn->$db;
  }
  public static function getInstance(){
    if(!(self::$conn instanceof self)){
      self::$conn = new self();
    }
    //return self::$conn->mydb;
    return self::$conn;
  }
  private function __clone(){
    trigger_error('Clone is not allowed');
  }// Prohibition of cloning 
  // Create an index 
  public function ensureIndex($table, $index, $index_param=array())
  {
    $index_param['safe'] = 1;
    try {
      self::$mon->$table->ensureIndex($index, $index_param);
      return true;
    }
    catch (MongoCursorException $e)
    {
      self::$error = $e->getMessage();
      return false;
    }
  }
  // Add 
  public function insert($table,$arr){
    try {
      self::$mon->$table->insert($arr, array('w'=>true));
      return true;
    }
    catch (MongoCursorException $e)
    {
      self::$error = $e->getMessage();
      return false;
    }
  }
  // Update 
  public function update($table, $condition, $new_arr, $options=array())
  {
    $options['w'] = 1;
    if (!isset($options['multiple']))
    {
      $options['multiple'] = 0;
    }
    try {
      self::$mon->$table->update($condition, $new_arr, $options);
      return true;
    }
    catch (MongoCursorException $e)
    {
      self::$error = $e->getMessage();
      return false;
    }
  }
  // Delete 
  public function remove($table, $condition, $options=array())
  {
    $options['w'] = 1;
    try {
      self::$mon->$table->remove($condition, $options);
      return true;
    }
    catch (MongoCursorException $e)
    {
      self::$error = $e->getMessage();
      return false;
    }
  }
  // Find 
  public function find($table, $query_condition, $result_condition=array(), $fields=array())
  {
    $cursor = self::$mon->$table->find($query_condition, $fields);
    if (!empty($result_condition['start']))
    {
      $cursor->skip($result_condition['start']);
    }
    if (!empty($result_condition['limit']))
    {
      $cursor->limit($result_condition['limit']);
    }
    if (!empty($result_condition['sort']))
    {
      $cursor->sort($result_condition['sort']);
    }
    $result = array();
    try {
      while ($cursor->hasNext())
      {
        $result[] = $cursor->getNext();
      }
    }
    catch (MongoCursorTimeoutException $e)
    {
      self::$error = $e->getMessage();
      return false;
    }
    return $result;
  }
  // Find 1 A record 
  public function findOne($table, $condition, $fields=array())
  {
    return self::$mon->$table->findOne($condition, $fields);
  }
  // Returns the number of records in the table 
  public function count($table)
  {
    return self::$mon->$table->count();
  }
  // Return error message 
  public function getError()
  {
    return self::$error;
  }
}

Action example:


use App\Http\Controllers\Api\MongdbCommonController;
$db = MongdbCommonController::getInstance();
$collection = 'tab';
$data = array('tt' =>'sdsd',
 'pp'  => 'ssdsdf');
// Returns the number of records 
echo $db->count($collection);
// Insert record 
$db->insert($collection, array("id"=>2, "title"=>"asdqw"));
// Update 
$db->update($collection, array("id"=>2),array('tt'=>'dfdfd',"gg"=>"bbb",'hh'=>'dfsdsd'));
// Find records 
echo '<pre>';
print_r( $db->find($collection, array("tt"=>'dfdfd'), array("start"=>1,"limit"=>4)));
// Delete 
$db->remove($collection, array('tt' =>'sdsd'));

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: