Alternative to include() in a loop for DB row templating?
<p>I'm writing a data provider class in PHP to help me speed up rendering of multiple-row SQL query results. Basically, the class has a bunch of SQL-related properties and methods to help with paginating, sorting and finally rendering the data. As for the latter, I want to be able to template the rows easily so I wrote a method called render() that can be called from a view file (in the MVC model) with a row template file as parameter. It looks similar to this:</p>

<pre><code>public function render($row_template_file) {
    if($result = mysql_query($this-&gt;query)) {
        while($row = mysql_fetch_array($result)) {
            include $row_template_file;
        }
    }
}
</code></pre>

<p>The actual method is more sophisticated than that (it checks whether the template file exists, uses data abstraction class rather than mysql_* functions etc.) but you get the general idea. The row template file is basically HTML that goes straight to the output, i.e.:</p>

<pre><code>&lt;div class="row"&gt;
    &lt;div class="foo"&gt;&lt;?php echo $row['foo']; ?&gt;&lt;/div&gt;
    &lt;div class="bar"&gt;&lt;?php echo $row['bar']; ?&gt;&lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>This approach works fine, the only problem is include() in a loop is not a great idea performance-wise, especially when rendering a large number of rows. Is there anything I could replace it with while keeping the ability to template rows that way? There were few similar questions here, but all suggested solutions involved mixing logic with presentation which is what I want to avoid. I was thinking of creating an anonymous function during first iteration, then calling it in all subsequent iterations, but maybe I'm overthinking it or reinventing the wheel here. Any ideas?</p>
