如何从另一个PHP类连接到MongoDB?

时间:2012-04-03 09:45:55

标签: 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"]);

然后我创建了一个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);
}
}

代码如下:

$shop = new Shop($id);
print_r ($shop->info());

2 个答案:

答案 0 :(得分: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;
    }
}

然后在应用程序的其他位置调用它:

$m = myprojMongoSingleton::getMongoCon();

答案 1 :(得分:0)

将连接移至您的商店类,而不是在$m上使用$this->m或等效设置,因此您始终可以参考它。