I'm using Kohana's php framework (2.x) and I want to have a helper that lets me access Mongo through a function and return the results as an object. For this to actually query the database, do I have to connect to the database in the local class? Or can I pass $this->mongo->collection
from a connected object? I'm sure I have errors and misconceptions in my code so feel free to point that out.
class mongoaccess
{
function __construct()
{
try
{
//$m = new MongoClient(); // not sure how to go about the connection
//$this->mongo = Mongo_Database::instance();
}
catch (Exception $e)
{
error_log('Caught exception: ' . $e->getMessage() . "
");
}
}
/**
* Converts an array to an object.
* Multiple nesting supported.
* @param $array | type: array | Ex: array('newvariable' => 'value')
*/
public static function arrayToObject($array)
{
$object = new stdClass;
foreach($array as $key => $value)
{
if(is_array($value))
{
$object->{$key} = arrayToObject($value); //Recursive
} else {$object->{$key} = $value;}
}
return $object;
}
/** Provides easy access to findOne()
* @param $collection | type: object member | Ex: $this->mongo->usersinapps
* @param $query | type: array | Ex: array('keyy' => 'valuee')
*/
public static function getObjectFromMongo($collection, $query)
{
if (empty($query) || !is_array($query) || empty($collection))
{return null;}
$collection->findOne($query);
$object = new stdClass();
$object = mongoaccess::arrayToObject($query);
return $object;
}
// needs review
/** Provides easy access to find() - iterates through cursor and returns array of objects
* @param $collection | type: object member | Ex: $this->mongo->usersinapps
* @param $query | type: array | Ex: array('keyy' => 'valuee')
*/
public static function getObjectsFromMongo($collection, $query)
{
if (empty($query) || !is_array($query) || empty($collection))
{return null;}
$objectArray = array();
$mongoResultsCursor = $collection->find($query);
while ($mongoResultsCursor->hasNext())
{
$document = $mongoResultsCursor->getNext();
array_push($objectArray, $document);
}
$object = mongoaccess::arrayToObject($objectArray);
return $object;
}
}