Welcome Guest, Not a member yet? Register   Sign In
[TIP] Swapping Function and ID using _remap
#1

[eluser]kilishan[/eluser]
I just did a search for this in the forums and noticed a bunch of people having trouble with getting their routes to work. Often, they were similar problems. I just solved my own problem and thought I'd post the solution I found.

Problem
I wanted to swap the place of the function name and the id in the url for a more pleasing url for a social site I'm working on.

Instead of http://www.my-site.com/people/settings/username, I wanted it to show http://www.my-site.com/people/username/settings.

Solution
I tried various settings in my route.php file, but ended up using the _remap function in my people controller. Here's the code, with comments to help explain what's going on.

Code:
function _remap($method) {
  // Check to see if the uri segment 2 is a function of this controller. ('username')
  if (method_exists($this, $method) ) {
    // It is a function, so run it.
    $this->$method();
  } else {
    // It's not a function, so it must be the username.

    // Reassign our method to the function listed in the 3rd uri segment ('settings')
    if ($this->uri->segment(3)) {
      $method = $this->uri->segment(3);
    }

    // Call the method and pass the username as an argument
    $this->$method($this->uri->segment(2));
  }
}

Then, in your function, you need to check and see if any arguments were passed. In this case, the username was passed to all of the methods. So we use the following code to check:

Code:
function settings() {
  // Was a username passed in?
  if (func_num_args() != 0) {
    // We have a username, so let's grab it.
    // Note: This returns an array...
    $username = func_get_args();
  }
}

Hope that makes sense and helps someone out there!




Theme © iAndrew 2016 - Forum software by © MyBB