Posted by Arjun Arjun on Monday 16th January 2012, 1 minute read

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

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';
...
Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.