如何从另一个PHP类连接到MongoDB? [英] How to connect to MongoDB from another PHP class?

查看:72
本文介绍了如何从另一个PHP类连接到MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码连接到MongoDB:

I have the following code to connect to 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的连接。

Then I've created a PHP class where I want to retrieve/update data in Mongo. I don't know how to access the connection to Mongo, previously created.

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


推荐答案

使用相同的连接字符串,它将使用相同的连接,但我建议您围绕您的Mongo连接类包装一个单例检索相同的连接对象。可能类似:

You can just use a "new Mongo()" with the same connection string and it will use the same connection, but I suggest you wrap a singleton around your Mongo connection class to retrieve the same connection object. Probably something like:

<?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;
    }
}

然后在应用程序中的任何其他地方调用:

And then call it anywhere else in your application with:

$m = myprojMongoSingleton::getMongoCon();

这篇关于如何从另一个PHP类连接到MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆