Search code examples
phpcodeigniterroutescodeigniter-url

Best method for URI Routing this in CodeIgniter?


So, here's an example on Forrst, a CodeIgniter website:

http://forrst.com/posts/PHP_Nano_Framework_WIP_Just_throwing_some_ideas_o-mU8

Look at that nice URL. You've got the root site, then posts, then the post title and a short extract. This is pretty cool for user experience.

However, my CodeIgniter site's URLs just plain suck. E.G.

http://mysite.com/code/view/120

So it accesses the controller code, then the function view, then the 20 on the end is the Post ID (and it does the database queries based on that).

I realised I could do some routing. So in my routes.php file, I put the following in:

$route['posts/(:num)'] = "code/view/$1"; - so this will make http://mysite.com/posts/120 be the same as http://mysite.com/code/view/120. A bit nicer, I think you'll agree.

My question is - how can I use a similar technique to Forrst, whereby an extract of the post is actually appended to the URL? I can't really see how this would be possible. How can the PHP script determine what it should look up in the database, especially if there are several things with the same title?

Thanks!

Jack


Solution

  • To get a URL like in your example you need to add a routing rule, like you've already done $route['posts/(:num)'] = "code/view/$1";. Forrst's url seems to be "mapped" (or something like that), I think the last part of the uri is the identifier (o-mU8 seems like a hash, but I prefer an int id) which is stored in the db, so if he queries, he splits the uri by the ndashes (_), and gets the last part of it, like this within your controller action:

    $elements = explode('_',$this-uri-segment(2));
    $identifier = $elements[count($elements)-1];
    
    $results = $this->myModel->myQuery($identifier);
    

    Basically the string between the controller/ and the identifier is totally useless, but not if your goal is a better SEO.

    I hope this helps