I am trying to write “good code” and use dependency injection to pass database objects in the constructors of my classes.
Constructors usually take this form:
public function __construct(MongoDB $db) { $this->collection = $db->collectionName; }
I noticed that for each created object a new MongoCollection
is created. (i.e. access to the $db->collectionName
property returns two different objects twice, not the same object)
I am using an ActiveRecord style base class so that objects can CRUD themselves.
Now, when I use some getAllRecords()
function and return 100 of these objects, 100 of MongoCollection
objects are MongoCollection
. (A quick look at the source of the driver seems to indicate that new objects are created there, and not just new views in PHP)
I got around this by wrapping the 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:
- Is this intentional behavior of MongoDB? Should it really return a new object every time, or is it a bug / feature in the PHP driver or Mongo itself (is there a precedent for using two objects for one collection?)
- I myself will create problems by caching the created and created
MongoDB
and MongoCollection
, and reuse them. - How do other people usually work with MongoDB? Should I use a completely different approach? (Ie DataMapper)
Thanks,
Leigh.
Leigh source share