I want to make sure I don't start multiple database connections when creating objects. Being new to OOP I'd like to get this right the first time.
I am using MongoDB
//connect to mongodb
$dbhost = 'localhost';
$dbname = 'test';
$mongo = new Mongo("mongodb://$dbhost");
So this is creating the database object. I read that it is best to use dependency injection into the class like below.
class Database {
protected $dbc; //database connection
protected $db; //database
function __construct(Mongo $mongo, $dbname) {
$this->dbc = $mongo;
$this->db = $this->dbc->$dbname;
}
}
The object is created by using this:
$db = new Database($mongo, $dbname);
And I'm able to use the MongoDB connection with no problems inside the Database class.
Since I'm creating a REST server, I'd like to split my Database class up into each method (PUT, GET, DELETE, etc). So really, I think it'd be best to extend the Database class and then create an object for only the method the server is requesting.
class GetDatabase extends Database {
//do my GET stuff in here
//use the Mongo connection in the parent contruct
}
I will need to run more than just queries from the GetDatabase class, since I have an Auth class (does not extend the database) that needs to use the DB connection as well.
Can anyone provide advice on how to make this work better or ensure that only one database connection is created ever?
Thanks!