I've been trying to write "good code" and use dependency injection to pass database objects in the constructors of my classes.
Constructors are generally taking this form:
public function __construct(MongoDB $db) {
$this->collection = $db->collectionName;
}
I've noticed that for each object created, a new MongoCollection
is created. (i.e. accessing the $db->collectionName
property twice returns two distinct objects, not the same object)
I've been using an ActiveRecord style base class, so that objects are able to CRUD themselves.
Now when I use some sort of getAllRecords()
function, and return 100s of these objects, 100s of MongoCollection
objects are created. (A quick look at the driver source seems to indicate new objects are created there too, not just new representations in PHP)
I've gotten around this by wrapping both Mongo
and MongoDB
classes to implement caching.
class MyMongo extends Mongo
{
private $objectCache = array();
public function __get($name) {
return array_key_exists($name, $this->objectCache)
? $this->objectCache[$name]
: $this->objectCache[$name] = new MyMongoDB($this, $name);
}
}
class MyMongoDB extends MongoDB
{
private $objectCache = array();
public function __get($name) {
return array_key_exists($name, $this->objectCache)
? $this->objectCache[$name]
: $this->objectCache[$name] = new MongoCollection($this, $name);
}
}
My questions are as follows:
MongoDB
and MongoCollection
objects that are created, and re-using them.Thanks,
Leigh.
It's intentional, as collections have properties other than their names associated with them (w and wtimeout at the moment, more planned for the future). If all you care about are the names, then it's fine to cache them.
I've been passing the MongoCollection
into my objects instead of the MongoDb
. My reasoning was that choosing the collection in the object would be a hidden dependency (may be overkill) and then in my unit tests, I can mock the MongoCollection
object.
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