0

In IndexController I retrieves data from the table and sends them to the view. In view I do foreach loops and displays it. One type of data needs to be taken from the database, so the link to the database in a view to get it.

<?php foreach ($this->datas as $data ): > 
  <div id="<?php echo $data->data_id ?>"></div>
  <?php 

$Data = Zend_Db::factory('pdo_mysql', $config);

    $select = $Data->select()
            ->FROM('data')
            ->WHERE('data_id = ?',$data->anchor); 
       $name = $Data->fetchRow($select);
   ?>

<span class="nick_name"><?php echo $name?></span>  

<?php endif; ?>

How can I avoid connecting to the database in a view?

Marcin
  • 1
  • You need a middle tier that connects on your behalf and returns the results to your view. Can Zend do that? – duffymo Jun 29 '12 at 14:26
  • 1
    Can you join the data in on the original query? Also you really don't want to connect to the database within the loop – Tim Fountain Jun 29 '12 at 14:27

1 Answers1

1

Easy: just don't do it.

Just move that DB logic away from your View. Perform a foreach loop in your Controller or (even better) Model which fetches the data you want for each of the elements. Or, if possible, use a JOIN to directly combine the results.

Config
  • 1,672
  • 12
  • 12
  • 1
    This would probably be good place for a domain model with a method like `getData()` so the data can be lazy loaded. :) – RockyFord Jun 30 '12 at 07:57