Skip to content

Instantly share code, notes, and snippets.

@lin
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save lin/5d624a3a2c337c090ee4 to your computer and use it in GitHub Desktop.

Select an option

Save lin/5d624a3a2c337c090ee4 to your computer and use it in GitHub Desktop.
// This function simply processes a Mongo query, and returns an array of objects of the specified type. The type is saved in the _model_class
// parameter (which is saved along with the mongo data). This allows us to know which concrete subclass was saved, and how to load it again.
protected static function get_withQuery ( $query, $collection_name, $sort = null, $limit = null, $skip = null ) {
$mongo = new MongoConnection();
$collection = $mongo->get_db()->selectCollection( $collection_name );
$resultCursor = $collection->find( $query );
if ( !empty($sort) ) $resultCursor->sort( $sort );
if ( !empty($limit) ) $resultCursor->limit( $limit );
if ( !empty($skip) ) $resultCursor->skip( $skip );
$results = array();
foreach ($resultCursor as $result) {
// ===================== SEE HERE ============================ //
$object = MongoObjectWrapper::arrayToObject_recursive( $result, NULL, $collection_name );
// ========================================================== //
$object->_mongo_postLoad();
$results[] = $object;
}
return $results;
}
function arrayToObject_recursive ( $data, $key = NULL, $collection_name = NULL) {
// if the passed data is just a value, return it, and terminate the recursion.
if ( !is_array( $data ) )
return $data;
// otherwise, read the class name out of the data.
if ( array_keys($data) !== range(0, count($data) - 1) ) {
if ( !is_null($collection_name) ) {
$class = "Sibi".ucwords(rtrim($collection_name, "s"));
} else if (array_key_exists("_id", $data)) {
$class = ucwords($key);
} else {
$class = "stdClass";
}
// instantiate an object of the found class.
$result = new $class;
// then recursively parse it's values, and add them as fields on the object.
foreach ($data as $key => $value)
$result->$key = arrayToObject_recursive( $value, $key );
}else{
// if no class name could be found, treat it as just a raw array.
$result = array();
// then recursively parse it's values, and add them as fields on the object.
foreach ($data as $key => $value)
$result[$key] = arrayToObject_recursive( $value, $key );
}
// finally, return the structure.
return $result;
}
class SibiPost {
public $aMemberVar = 'aMemberVar Member Variable';
public $aFuncName = 'aMemberFunc';
function aMemberFunc() {
print 'Inside `aMemberFunc()`';
}
}
$arr1 = array(
"bar" => Array("foo", "bar"),
);
$object1 = arrayToObject_recursive($arr1, NULL, "posts");
echo(get_class($object1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment