Remapping Controller Method Calls in CI


Again, most of this is copied from the UG.

Everything here relates to controllers.

Controller is the parent subject of this post.

This post is about remapping method calls. In other words: You have a URI which calls a particular method; but, instead you want a different method to be called.

The title which the UG uses for this topic is Remapping Function Calls.


The second segment of the URI typically determines which function in the controller gets called. CodeIgniter permits you to override this behavior through the use of the _remap() function:

public function _remap()
{
    // Some code here...
}

Important:
If your controller contains a function named _remap(), it will always get called regardless of what your URI contains. It overrides the normal behavior in which the URI determines which function is called, allowing you to define your own function routing rules.

The overridden function call (typically the second segment of the URI) will be passed as a parameter to the _remap() function:

public function _remap($method)
{
    if ($method == 'some_method')
    {
        $this->$method();
    }
    else
    {
        $this->default_method();
    }
}

The call to _remap is done by CI. CI will supply the parameters.

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

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

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in CodeIgniter. Bookmark the permalink.

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s