0

I love the way SO handles URIs. I'd like to mimic the same behaviour in CI. I have a controller called Users and the index method should take one argument, that being the user ID. I search the DB for the username associated with that user ID. Consider that user:1 has username:Santa Claus, how can I append the username to the URI, so that it looks like http://foo.com/users/1/santa-claus

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {

function index($uID = 0) {
    if ($uID > 0) {
        $this->load->model('users_model');
        $uname = $this->users_model->_getUsername($uID);

        #append somehow..       

    } else {
        echo('load all users');
    }
}

}

Just to be clear, I'm trying to achieve this:

https://stackoverflow.com/a/11041075/704015

Community
  • 1
  • 1
Jezen Thomas
  • 13,619
  • 6
  • 53
  • 91

2 Answers2

1

application/config/routes.php

$route['users/(:num)/(:any)'] = 'users/index/$1';

Controller

    function index($uID = 0) {
         .....
         $uname = strtolower(str_replace(" ", "-", $uname));

         header("Location: ".base_url()."user/".$uID."/".$uname);

Please include a condition do something else incase username is already present to avoid loop.

user1190992
  • 669
  • 3
  • 8
  • You correctly predicted that it would cause a redirect loop. My first thought is to explode the URI and check the last segment against the value of `$uname`, but I don't know how reliable that would be. – Jezen Thomas Dec 12 '12 at 00:02
  • I added this condition: `$uri = explode('/', $_SERVER['REQUEST_URI']); if ($uname != end($uri)) {...}` – Jezen Thomas Dec 12 '12 at 00:17
0

This in your config/routes.php

 $route['users/(:num)/(:any)'] = 'users/$1/$2';

and this in your controller

public function users($id,$username = FALSE)
{
xdotcommer
  • 48
  • 9
  • This doesn't work. I don't know why this would work either. If I accessed the method and didn't include a second argument, how would it search the DB for the username associated with the user ID, and append the username to the URI? – Jezen Thomas Dec 11 '12 at 22:56
  • Pretty simple really you can append the information you retrieve via javascript (so you dont have to do a redirect) Like so: window.history.pushState("object or string", "Title", "/new-url"); more details here http://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page?answertab=oldest#tab-top – xdotcommer Dec 12 '12 at 00:06
  • Ideally, I would create all important functionality without relying on JS. – Jezen Thomas Dec 12 '12 at 00:16