user2287474 user2287474 - 6 months ago 10
PHP Question

Dynamically generate method that doesn't exist?

I'm trying to write a wrapper for the new MongoDB driver to work with code written for the old driver.

The old way of using Mongo in PHP was like this:

$connection = new Mongo('mongodb://username:password@127.0.0.1/theDatabaseYouWantToConnectTo');
$db = $connection->theDatabaseYouWantToConnectTo;
$collection = $db->aCollectionYouWantToDoStuffWith;
$collection->insert(array(
'someColumnName' => 'someDataForTheCell'
));


My question is, how does these parts work?

$db = $connection->theDatabaseYouWantToConnectTo;
$collection = $db->aCollectionYouWantToDoStuffWith;


Obviously
theDatabaseYouWantToConnectTo
and
aCollectionYouWantToDoStuffWith
are NOT methods, so how would my wrapper class understand what these are?

Here is kind of a skeleton for the wrapper class I'm trying to write.

class Mongo{

var $native_mongo_instance;

function __construct($uri){

$native_mongo_instance = new MongoDB\Driver\Manager($uri);

$this->set_native_mongo_instance($native_mongo_instance);

}

public function set_native_mongo_instance($native_mongo_instance){

$this->native_mongo_instance = $native_mongo_instance;

}

public function get_native_mongo_instance(){

return $this->native_mongo_instance;

}

public function find(){


}

public function insert(){


}

public function remove(){


}
}

Answer

Here you can find a full reference of magic methods in PHP. The one that you're looking for is __get() (here's C code of the legacy driver).

Also to not reinvent the wheel (or for learning purposes), you may take a look at alcaeus/mongo-php-adapter which provides old API atop new driver and library.

Comments