16

I have heard of people using slugs for generating clean urls. I have no idea how it works. Currently i have a codeigniter site which generates url's like this

www.site.com/index.php/blog/view/7

From what i understand by maintaining a slug field it is possible to achieve urls like

www.site.com/index.php/blog/view/once-upon-a-time

How is this done? Especially in reference to codeigniter?

esafwan
  • 17,311
  • 33
  • 107
  • 166
  • You can use the CI Slug Library by Eric Barnes: https://github.com/ericbarnes/CodeIgniter-Slug-Library – alpere Dec 14 '13 at 14:05

2 Answers2

55

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 2
    That is exactly the way I would do it, but I'm a bit concerned about the performance with these type of URLs. Say you have an URL like the ones at Stackoverflow: /questions/{integer}/{slug}, isn't that a bit more efficient than /questions/{slug}, because with the first type of URL, you could simply use the primary key in the database for faster search. With the other URL, you would have to do a string comparisation, which is definately slower. – EsTeGe Jun 13 '12 at 16:22
  • @EsTeGe: That's right. If performance is a concern you'll want to stick to using fast indexes/keys for querying. However if it's not critical or you have some reasonable caching in place to lighten the load on the database, you can go with slugs instead. – BoltClock Jun 13 '12 at 16:24
  • Oh, I didn't think about the built-in caching capability of codeigniter. That's based on the URL, so that's one less query to worry about. – EsTeGe Jun 13 '12 at 16:32
3

To my ES friends, remove accented characters using this, from Text Helper:

 $string = 'áéíóú ÁÉÍÓÚ';   
 $slug = url_title(convert_accented_characters($string), 'dash', true); //convert_accented_characters function will deal with the accented characters.
 echo $slug; //aeiou-AEIOU
anu g prem
  • 545
  • 5
  • 15