How to connect to MongoDB from another PHP class?

2019-06-24 18:08发布

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

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

And the code is something like:

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

2条回答
▲ chillily
2楼-- · 2019-06-24 18:35

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();
查看更多
家丑人穷心不美
3楼-- · 2019-06-24 18:35

Move the connection into your shop class and instead of setting it on $m use $this->m or equivalent so you always have reference to it.

查看更多
登录 后发表回答