【问题标题】:How to connect to MongoDB from another PHP class?如何从另一个 PHP 类连接到 MongoDB?
【发布时间】:2012-04-03 09:45:54
【问题描述】:

我有以下代码可以连接到 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());

【问题讨论】:

    标签: php oop class mongodb


    【解决方案1】:

    您可以只使用具有相同连接字符串的“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();
    

    【讨论】:

    • 嗨 Derick,如果 'If' 条件不满足,则不会返回 no?
    【解决方案2】:

    将连接移动到您的商店类中,而不是将其设置为 $m 使用 $this-&gt;m 或等效项,以便您始终可以参考它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2019-02-24
      • 1970-01-01
      • 2016-01-29
      相关资源
      最近更新 更多