Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to MongoDB from another PHP class?

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());
like image 907
Alexandru R Avatar asked Dec 28 '22 03:12

Alexandru R


1 Answers

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();
like image 103
Derick Avatar answered Dec 30 '22 10:12

Derick