PHP MongoDB连接类封装概述
本内容分享一个基于PHP编写的简易MongoDB连接封装类,旨在为相关开发提供参考与借鉴。
首先展示MongoDB连接类的具体封装代码。
CodeIgniter框架中MongoDB库的加载与配置
<?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);
}
//获取所有的集合名
function getCollections()
{
return $this->database->getCollectionNames();
}
//选数据库
function selectDB($db)
{
$this->database = $this->mongo->selectDB($db);
}
}
接着演示如何简洁地调用该类以执行数据插入操作。
使用封装类进行数据插入的具体实现
class DemoController extends CI_Controller
{
function __construct() {
parent::__construct();
//CI中加载类
$this->load->library('mongo_lib', '', 'mongodb');
}
//插入一条数据
function create()
{
$data = array('name'=>'mike','email'=>'abc@163.com);
//选择库,shell:user demo_db
$this->mongodb->selectDB('demo_db');
//选择集合,db.demo_col.insert();
$rebateCollection = $this->mongodb->getCollection('demo_collection');
$res = $rebateCollection->insert($data);
}
}
期望上述内容能对从事PHP程序开发的读者提供实质性的帮助。