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:
<?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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With