3 namespace DataAccess\DataMapper
;
5 use Domain\Entities\IDivineEntity
;
6 use DataAccess\DataMapper\IDataMapper
;
7 use DataAccess\DataMapper\Helpers\AbstractPopulationHelper
;
11 class DataMapper
implements IDataMapper
16 public function __construct($maps)
18 //TODO: should probably do all this through a configuration object or something
19 $dsn = 'mysql:host=localhost;dbname=divinelegy;charset=utf8';
22 $options = array(PDO
::ATTR_EMULATE_PREPARES
=> false
,
23 PDO
::ATTR_ERRMODE
=> PDO
::ERRMODE_EXCEPTION
);
25 $this->_db
= new PDO($dsn, $username, null
, $options);
26 $this->_maps
= include $maps;
29 public function map($entityName, $queryString = 'SELECT * FROM %s')
31 $statement = $this->_db
->prepare(sprintf($queryString,
32 $this->_maps
[$entityName]['table']
35 $statement->execute();
36 $rows = $statement->fetchAll();
40 foreach($rows as $row)
42 $className = $this->_maps
[$entityName]['class']; //the entity to instantiate and return
43 $constructors = AbstractPopulationHelper
::getConstrutorArray($this->_maps
, $entityName, $row, $this->_db
);
45 if(count($constructors) == 0)
47 $class = new $className;
49 $r = new ReflectionClass($className);
50 $class = $r->newInstanceArgs($constructors);
53 $class->setId($row['id']);
54 $entities[$row['id']] = $class;
60 public function save(IDivineEntity
$entity)
62 $queries = AbstractPopulationHelper
::generateUpdateSaveQuery($this->_maps
, $entity, $entity->getId(), $this->_db
);
64 // if($queries['TYPE'] == AbstractPopulationHelper::QUERY_TYPE_CREATE)
66 unset($queries['TYPE']);
68 foreach($queries as $index => $query)
71 if (preg_match_all('/'.preg_quote('%').'(.*?)'.preg_quote('%').'/s', $query, $matches)) {
72 foreach($matches[1] as $index_ref)
74 if($index_ref != 'MAIN_QUERY_ID')
76 $index_id = str_replace('INDEX_REF_', '', $index_ref);
77 $query = str_replace('%INDEX_REF_' . $index_id . '%', $idMap['INDEX_REF_' . $index_id], $query);
86 $statement = $this->_db
->prepare($query);
87 $statement->execute();
89 $idMap['INDEX_REF_' . $refIndex] = $this->_db
->lastInsertId();
90 unset($queries[$index]);
92 //update query so that other references are resolved.
93 $queries[$index] = $query;
97 //at this point we have queries left that depend on the main query id
98 foreach($queries as $query)
100 $query = str_replace('%MAIN_QUERY_ID%', end($idMap), $query);
101 $statement = $this->_db
->prepare($query);
102 $statement->execute();
112 public function remove(IDivineEntity
$entity) {