Saturday, November 8, 2008

Hint for Class 8 - In-Class Assignment

By now, you're wondering "Where in my code should I retrieve all the comments associated with each blog post?"

Good question. What I recommend is first of all you make a separate Model file for your comments. This will have functions to do all the database CRUD operations, just like the Model for the blog posts does for blog posts.

Just as the blog post Model has a getAllPosts() function, your comment Model will have a getAllComments() function. But unlike the getAllPosts() function, your getAllComments() function will take one parameter: the id of the blog post for which you want to retrieve the comments.

In other words, the function definition will start out like this:


...
function getAllComments($blogPostId) { ... }
...



This function will get all comments associated with the blog post that you specify in $blogPostId. I'll leave it up to you to figure out what the exact MySQL query is that will get those results. But what I recommend is that you return an array of all the comments as the return value for that function.

Then, you will have to call that function from somewhere. The easiest thing is to do that in the View that displays the blog posts.

In your blog View, you have code like this:


<?php foreach ($posts as $post) : ?>
...
<?php endforeach ?>



This code is looping through each blog post and displaying it, so it's the perfect place to add some code to get the comments for the current blog post and display them. So I would do something like this:



<?php foreach ($posts as $post) : ?>
...
<?php foreach (getAllComments($post['id']) as $comment) : ?>
...
<?php endforeach ?>
...
<?php endforeach ?>



This gets an array of all the comments for each blog post, and then loops through each element of that array. So inside that foreach statement where you are looping through all the comments, you put the code to display the comments.

No comments: