Note that there are some explanatory texts on larger screens.

plurals
  1. POData Mapper Pattern: Complexe query from Service Layer
    primarykey
    data
    text
    <p>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:</p> <p>We got a table with several Persons:</p> <pre><code>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``), ); </code></pre> <p>Now I try to select all people, that have brown hair. I use the following method in the ServiceLayer</p> <pre><code>public function getPeopleByHaircolor($hair) { return $this-&gt;getMapper()-&gt;fetch('haircolor = ?', $hair); } </code></pre> <p>The method in the Mapper looks like this:</p> <pre><code>public function fetch($condition, $value) { $resultSet = $this-&gt;getTable()-&gt;fetchAll($this-&gt;getTable()-&gt;select()-&gt;where($cond, $value)); $entries = array(); foreach($resultSet as $row) { $entry = new Default_Model_Person(); $entry-&gt;id = $row-&gt;id; $entry-&gt;name = $row-&gt;name; [...] } return $entries; } </code></pre> <p>I think I follow the Data Mapper Pattern with this methods... </p> <hr> <p><strong>Now the Problem:</strong></p> <p>I want to select Persons, that have brown hair AND that are younger than 20 yrs. So how can I do that? My try:</p> <pre><code>public function getTeens($hair) { $rows = $this-&gt;getMapper()-&gt;fetch('haircolor = ?', $hair); $return = array(); foreach($rows as $row) { if((int)$row-&gt;age &lt; 20) $return[] = $row; } return $return; } </code></pre> <p>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.</p> <hr> <p><strong>My Question:</strong></p> <p>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. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload