我正在使用 Kohana 的 php 框架 (2.x),我想要一个帮助程序,让我可以通过函数访问 Mongo 并将结果作为对象返回。为此要实际查询数据库,我是否必须连接到本地类中的数据库?或者我可以$this->mongo->collection
从连接的对象传递吗?我确定我的代码中存在错误和误解,因此请随时指出。
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() . "\n");
}
}
/**
* 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;
}
}