Caching MongoDB objects in PHP

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.

+6
source share
2 answers

This is intentional because collections have properties other than their associated names (w and wtimeout at the moment, more planned for the future). If all you care about are names, then it's great to cache them.

+2
source

I passed MongoCollection to my objects instead of MongoDb . My reasoning was that choosing a collection in an object would be a hidden dependency (maybe redundant), and then in my unit tests I could mock the MongoCollection object.

+1
source

Source: https://habr.com/ru/post/911944/


All Articles