2012-04-03 93 views
4

我有以下代码连接到MongoDB中:如何从另一个PHP类连接到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连接。

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()); 

回答

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(); 
+0

嗨德里克,如果“如果”条件满足什么都不会返回任何? – 2013-11-01 10:21:37

+0

好点,我修正了这个例子 – Derick 2013-11-25 11:10:30

0

移动连接到你的店铺类,而不是把它放在$m使用$this->m或等同,所以你总是有参考吧。