Files
fdn2/private/lib/dao/GenericDao.php
T

114 lines
3.0 KiB
PHP

<?php
/*
Author: Riccardo Di Dato
Creation Date: 22/dic/2015
*/
class GenericDao{
private $mongoObj;
private $database;
/**
* La connection string viene passata interamente a MongoClient, richiede formato 'mongo://server:port'.
* host1 e database sono obbligatori
*
* @param string $connectionString
*/
public function __construct($dbName, $connectionString = null){
if (is_null($connectionString)){
$this->mongoObj = new MongoClient();
}
else {
if (!preg_match("~^mongo[:][/][/]\w+[:]\w+$~",$connectionString)){
throw new CoreException("Invalid connectionString parameter passed to 'GenericDao::__construct()' ('".print_r($connectionString,true)."')");
}
$this->mongoObj = new MongoClient($connectionString);
}
$this->database = $this->mongoObj->$dbName;
}
/**
* Ritorna un array di model
* @param string $modelClass classe da ritornare (DaoSaveable)
* @param array $filter array associativo della select formato mongo
* @param array $options (al momento supporta limit e sort)
* @param string $customReturnClass
* @throws CoreException se la CustomReturnClass non è valida
* @return DaoSaveable[]
*/
public function query($modelClass, array $filter = array(), array $options = array()){
if (!is_null($modelClass)){
if (!is_subclass_of($modelClass, "DaoSaveable", true)){
throw new CoreException("Invalid return class passed to GenericDao::query ($modelClass)");
}
}
$collectionName = $modelClass::getCollectionName();
$collection = $this->database->$collectionName;
if (!array_key_exists("deleted",$filter)){
$filter["deleted"] = false;
}
$cursor = $collection->find($filter);
if (array_key_exists("sort",$options)){
$cursor->sort($options["sort"]);
}
if (array_key_exists("limit",$options)){
$cursor->limit($options["limit"]);
}
$rval = array();
foreach ($cursor as $element){
var_dump($element);
$rval[] = $modelClass::buildFromSaveableObj($element);
}
return $rval;
}
public function save(DaoSaveable $model){
$collectionName = $model->getCollectionName();
$collection = $this->database->$collectionName;
$saveObj = $model->getSaveableObj();
if ( !is_null($saveObj["_id"]) ){
$collection->update( array("_id"=>$saveObj["_id"] ), $saveObj );
}
else {
$saveObj["_id"] = new MongoId();
$collection->insert($saveObj);
$model->updateFromSaveableObj($saveObj);
}
}
public function delete(DaoSaveable $model){
$collectionName = $model->getCollectionName();
$collection = $this->database->$collectionName;
$saveObj = $model->getSaveableObj();
if ( !is_null($saveObj->_id) ){
$saveObj["deleted"] = true;
$collection->update( array("_id"=>$id), $saveObj );
}
}
// public static function registerModel($model){
// if(is_subclass_of($model, "DaoSaveable",true)){
// $collectionName = $model::getCollectionName();
// self::$MODEL_REGISTRY[$collectionName] = $model;
// }
// else{
// throw new CoreException("Invalid model passed to GenericDao::registerModel ($model)");
// }
// }
}
?>