Skip to content

CodeIgniter _remap function?

Last updated on May 6, 2018

CodeIgniter permits you to override its default routing behavior through the use of the _remap() function. As you already knew the second segment of the URI typically determines with function is in the controller get called and it will be passed as a parameter to the _remap() function. So to hide the real method name in the URL you can use _remap() and you can define your own set of routing rules.

CodeIgniter _remap function?

If your controller contains a function named _remap(), it will always get called regardless of what your URI contains. It overrides the normal behavior. For example: your URL is http://localhost/index.php/post/index and you do not want to call index for this then you can use _remap() to map new function view instead of index like this.


public function _remap($method)
{
    if ($method == 'index')
    {
        $this->postList();
    }
    else
    {
        show_404();
    }
}

public function postList() {
  
}

Any extra segments after the method name are passed into _remap() as an optional second parameter. This array can be used in combination with PHP’s call_user_func_array() to reproduce the CodeIgniter’s default behavior.

we can process your mappings neatly by avoiding multiple if – else if – else and switch statements, by defining your methods with a prefix(Ex: process) and calling methods dynamically with call_user_func_array() as shown below.

  public function _remap($method, $params = array())
  {
      $method = 'process'.ucwords($method);
      if (method_exists($this, $method))
      {
          return call_user_func_array(array($this, $method), $params);
      }
      show_404();
  }

Resources:

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments