I just store the slugs in my database table, in a column called slug
, then find a post with the slug, like this:
public function view($slug)
{
$query = $this->db->get_where('posts', array('slug' => $slug), 1);
// Fetch the post row, display the post view, etc...
}
Also, to easily derive a slug from your post title, just use url_title()
of the URL helper:
// Use dashes to separate words;
// third param is true to change all letters to lowercase
$slug = url_title($title, 'dash', true);
A little bonus: you may wish to implement a unique key constraint to the slug
column, that ensures that each post has a unique slug so it's not ambiguous which post CodeIgniter should look for. Of course, you should probably be giving your posts unique titles in the first place, but putting that in place enforces the rule and prevents your application from screwing up.