Welcome Guest, Not a member yet? Register   Sign In
Displaying database results - Where should the looping logic go?
#1

[eluser]lukeinjax[/eluser]
I'm trying to figure out the best way to handle showing results from a database. I know that I could retrieve the results from the model from within the controller and then pass the whole results set to the view, but then I would have looping logic in my view, which somewhat violates the purpose of MVC.

My other option would be to break the view up into several small pieces and call them via $this->load->view('someview') in the controller as I loop through the results. The only problem with this is that if (for example) I wanted to show the results in a table, I would need to have the beginning of the table in one view, then a separate view that would be called for each row within the loop in the controller, then another view to close the table.

I'm wondering which of these solutions the CI community would use, or if I'm missing something all together. I'm also wondering about the performance implications of both solutions and trying to figure out which would be more efficient. One involves passing a potentially large object around (not sure if CI does this by reference or value) and the other involves loading a view over and over again. Again, I'm not sure how CI handles this. Does the view get cached while the script is executing, or is it actually loaded fully each time?
#2

[eluser]Colin Williams[/eluser]
I don't the answer to the latter questions, but I do have bit of an opinion on the main issue.

I don't think loop logic in a view is terrible, but I would reserve it only for properties of the main object the view is responsible for presenting. For example, a page that lists blog posts should call a blog_post view file in a loop.

Code:
$data['posts'] = "";
foreach ($this->blog->posts() as $post(
{
   $data['posts'] .= $this->load->view('blog/post', array('post' => $post), TRUE);
}
$this->load->view('blog/list', $data);

Say that $post object had an array of attached images. I wouldn't find it awful to have the views/blog/post.php file loop through $post->images to display each one

Code:
<ul class="images">
&lt;? foreach ($post->images as $img) : ?&gt;
   <li><image src="&lt;?= $img->src ?&gt;" alt="&lt;?= $img->alt ?&gt;" /></li>
&lt;? endforeach; ?&gt;
</ul>

I know there's no <image> tag, but the forum stripped out the proper img tag.
#3

[eluser]Unknown[/eluser]
Colin, thank you. I have been considering using views in a more atomic fashion and this post has shown me the way. Four years later, have to say thanks!




Theme © iAndrew 2016 - Forum software by © MyBB