Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

How do I replicate the MongoDB API paradigm?

MongoDB's excellent PHP driver allows me to write to write PHP code that looks like this:

$mongo = new mongo("mongodb://path.to.my.server.com:27017");
$cnt = $mongo->db_name->table->count();

What's more, I can also write similar code on nonexistent tables:

$mongo->new_db_name->table->save(array('name' => 'Jimmy'));
echo $mongo->new_db_name->table->count();

The Mongo class is the parent object created by the Mongo() constructor, and it seems to create child MongoCollection variables (db_name and new_db_name, respectively) on the fly, as needed. How does the Mongo driver do this? How does it know to create an object of type MongoCollection if a public variable isn't found? The driver is a PECL C extension; is that necessary to replicate this behavior, or can someone do something like that in PHP?

Upvotes: 1

Views: 115

Answers (1)

chx
chx

Reputation: 11760

You can use a class like this to achieve the same:

class mongolike {
  protected $dbs;
  function __get($name) {
    if (empty($this->dbs[$name])) {
      $this->dbs[$name] = new db($name);
    }
    return $this->dbs[$name]
  }
}

Upvotes: 2

Related Questions