Ale*_*u R 4 php oop class mongodb
我有以下代码连接到MongoDB:
try {
$m = new Mongo('mongodb://'.$MONGO['servers'][$i]['mongo_host'].':'.$MONGO['servers'][$i]['mongo_port']);
} catch (MongoConnectionException $e) {
die('Failed to connect to MongoDB '.$e->getMessage());
}
// select a database
$db = $m->selectDB($MONGO["servers"][$i]["mongo_db"]);
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个PHP类,我想在Mongo中检索/更新数据.我不知道如何访问之前创建的Mongo连接.
class Shop {
var $id;
public function __construct($id) {
$this->id = $id;
$this->info = $this->returnShopInfo($id);
$this->is_live = $this->info['is_live'];
}
//returns shop information from the database
public function returnShopInfo () {
$where = array('_id' => $this->id);
return $db->shops->findOne($where);
}
}
Run Code Online (Sandbox Code Playgroud)
代码类似于:
$shop = new Shop($id);
print_r ($shop->info());
Run Code Online (Sandbox Code Playgroud)
Der*_*ick 10
您可以使用具有相同连接字符串的"new Mongo()",它将使用相同的连接,但我建议您在Mongo连接类周围包装一个单例以检索相同的连接对象.可能是这样的:
<?php
class myprojMongoSingleton
{
static $db = NULL;
static function getMongoCon()
{
if (self::$db === null)
{
try {
$m = new Mongo('mongodb://'.$MONGO['servers'][$i]['mongo_host'].':'.$MONGO['servers'][$i]['mongo_port']);
} catch (MongoConnectionException $e) {
die('Failed to connect to MongoDB '.$e->getMessage());
}
self::$db = $m;
}
return self::$db;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在应用程序的其他位置调用它:
$m = myprojMongoSingleton::getMongoCon();
Run Code Online (Sandbox Code Playgroud)