Wednesday, July 11, 2012

Codeigniter php frameworks: controllers part 4

Codeigniter php frameworks will be go to the part 4 of controllers. If you have not read the previous part, click here. Now we learn about defining a default controller. Codeigniter can be told to load a default controller when a URI is not present, as will be the case when only your site root URL is requested. To specify a default controller, open your application/config/routes.php file and set this variable $route['default_controller'] = 'Blog';.

Where blog is the name of controller class you want to be use. If you now load your main index.php file without specifying any URI segments you’ll see your Hello World message by default. Codeigniter php frameworks is finish talking about default controller, now we going to remapping function calls. As defining a default controller, the second segment of the URI typically determines which function in the controller get called. Codeigniter permits you to override this behavior through the use of the  function like this.

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

The override function call (typically the second segment of the URI) will be passed as a parameter to the _remap() function like list code number 1 on this paragraph bellow. Any extra segment 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 emulate Codeigniter’s default behavior. You can see the example code at list code number 2 on this paragraph bellow. Okay enough for part 4 of controller, see you at part 5 of controller only on Codeigniter php frameworks.

Code number 1

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

Code number 2

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();
}

For the note of remapping function calls , 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.

This post of Codeigniter php frameworks: controllers part 4 is references from http://codeigniter.com/user_guide/general/controllers.html.

No comments:

Post a Comment