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());
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:
And then call it anywhere else in your application with:
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.