Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

php - Using slugs in codeigniter

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...