這篇文章給大家介紹使用PHP怎么封裝一個(gè)MongoDB連接類,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
1. 封裝MongoDB類
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(); } //選數(shù)據(jù)庫 function selectDB($db) { $this->database = $this->mongo->selectDB($db); } }
2. 簡單調(diào)用,insert數(shù)據(jù)。
class DemoController extends CI_Controller { function __construct() { parent::__construct(); //CI中加載類 $this->load->library('mongo_lib', '', 'mongodb'); } //插入一條數(shù)據(jù) 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); } }
關(guān)于使用PHP怎么封裝一個(gè)MongoDB連接類就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。