I'm sing the Data Mapper Pattern in Zend Framework. This works well so far, but now I got to a point where I need your help/opinion. So let's start with the Code:
We got a table with several Persons:
CREATE TABLE `persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` int(3) NOT NULL,
`haircolor` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id``),
);
Now I try to select all people, that have brown hair. I use the following method in the ServiceLayer
public function getPeopleByHaircolor($hair) {
return $this->getMapper()->fetch('haircolor = ?', $hair);
}
The method in the Mapper looks like this:
public function fetch($condition, $value) {
$resultSet = $this->getTable()->fetchAll($this->getTable()->select()->where($cond, $value));
$entries = array();
foreach($resultSet as $row) {
$entry = new Default_Model_Person();
$entry->id = $row->id;
$entry->name = $row->name;
[...]
}
return $entries;
}
I think I follow the Data Mapper Pattern with this methods...
Now the Problem:
I want to select Persons, that have brown hair AND that are younger than 20 yrs. So how can I do that? My try:
public function getTeens($hair) {
$rows = $this->getMapper()->fetch('haircolor = ?', $hair);
$return = array();
foreach($rows as $row) {
if((int)$row->age < 20) $return[] = $row;
}
return $return;
}
But if you get more variables, like "people with brown hair, younger than 20yrs and with the name 'Foo Bar'", I need more and more methods and/or foreach loops.
My Question:
How would you do this in the Data Mapper Pattern? If I do a native SQL query like $serviceLayer->mapper->table->qry('SELECT ...'), is this breaking the Data Mapper Pattern? I don't like those additional foreach loops and it feels like I'm doing something wrong, so I wrote this question.