Posted by Arjun on Monday 16th January 2012

CodeIgniter : One Controller to Rule all Methods(page)

Today, we are Going to Use Codeigniter URI Segments to rule all Methods within the controller, means one Controller will load views based on the URI segments, This method is best for static sites that don’t require a controller for every page and also we can set a 404 view when nothing is found.

Currently this Controller will only goes three levels deep

<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');
 
class Welcome extends CI_Controller
{
 
    var $_data = array();
 
    public function __construct()
    {
        parent::__construct();
    }
 
    public function index()
    {
        if (!$this->uri->segment(1) && !$this->uri->segment(2)) {
            $view = 'welcome';
        }
        if ($this->uri->segment(1) && !$this->uri->segment(2)) {
            $view = $this->uri->segment(1, 'welcome');
        }
        if ($this->uri->segment(1) && $this->uri->segment(2)) {
            $view = $this->uri->segment(1, 'welcome') . '/' . $this->uri->segment(2, '');
        }
        if (!file_exists(APPPATH . 'views/' . $view . EXT)) {
            $view = "404";
            header("HTTP/1.0 404 Not Found");
        }
 
        $this->load->view($view, $this->_data);
 
    }
}
 
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

Open application/controllers/routes.php
replace welcome with your default controller name

$route['(.*)'] = 'welcome';