I’m working on a new php project with CodeIgniter and I have few questions about it.
1 – I created news script, for now I done backend and I’m working on frontend. At frontend I already set last news, but I want to show how many comments at one news there are. I used foreach, but I don’t know what’s the best method to do next in MVC framework.
<?php
foreach ($query as $news)
{
echo $news->title . "<br>" . $news->content . "<br>";
$commentnum = $this->db->select('id_comment, id_news')->where('id_news', $news->id)->get('comments');
echo $commentnum->num_rows();
}
?>
Okay.. that’s some piece of code which I use in other projects. What’s the best way to use that code in MVC pattern?
2 – At this news script I have some controller which is named News and in it are functions post, cats and tags. And code which I’m using now, but not works like I want:
$route['news/(:any)'] = "news/post/$1";
So how to exclude post, cats and tags from the route -> If I type news/tags/first, to get the tag first and not error, that the post doesn’t exist. How to do that?
If you want to stick to the MVC pattern (and I would suggest you do as it makes things easier in the long run of managing your application, or updating its looks) then do the following:
Instead of
echoing out all your ‘news’ info, store it into an array, and pass that array to the VIEW. Let the VIEW then just go through that array (of news & related comments) and output it.That way your logic for assembling this news / comment structure remains in the controller, and the view just spits out the data, and does not ITERATE through the
$queryobject.This creates a clean separation of controller, model & view.
Example:
As far as your routing issue is concerned you need to properly route the URI to the METHOD in your controller:
The
$route['(:any)']I haven’t personally tried, but I would suggest you format your URI to be something likehttp://domain.com/post/name-of-postas opposed tohttp://domain.com/name-of-post, it will just be cleaner for routing keeping it seperate, because the above route$route['(:any)']forces you to create CUSTOM routes (a whitelist) for everything else like tags / links / users / etc;