ds000001 2010-07-22 04:29
浏览 85
已采纳

在codeigniter中使用slugs

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?

  • 写回答

4条回答 默认 最新

  • doyrte8419 2010-07-22 04:33
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 Keil编译时报错"no source": Error: #5: cannot open source
  • ¥50 操作系统时间无法更新
  • ¥20 Windows11, usb转hdmi,外接显示器无反应
  • ¥20 怎么在JavaFx的TableView中动态地添加数据。
  • ¥15 MFC里的工具栏按钮图标使用外部图片
  • ¥15 如何在 llama.cpp 服务器中实现用户登录功能的优化方案?(语言-c++)
  • ¥15 有会用octave 的吗,急!代做!好偿!
  • ¥15 有一套同城小程序源码,Uniapp前端,php+html+mysql后端 ,能不能教我搭建起来可以运行,我不知道怎样操作
  • ¥15 mac调用java.io接口无法在根目录生成文件
  • ¥15 java微服务节点假死,网关路由时长延迟