Codeigniter - One Controller to Rule Them All


/ Published in: PHP
Save to your folder(s)

This one controller will load views based on the URI segments returned, good for static sites that don\\\\\\\'t require a controller for every page. Requires a view \\\\\\\"404\\\\\\\" as a default when nothing is found.


Copy this code and paste it in your HTML
  1. // Following goes in your default controller
  2. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  3.  
  4. class Home extends CI_Controller {
  5. var $_data = array ();
  6.  
  7. public function index()
  8. { // One Controller to rule them all!
  9. // Currently only goes three levels deep
  10. if ( $this->uri->segment(2) == false && $this->uri->segment(3) == false ) {
  11. // If there's no second and third segment in the URL then use the first segment to find the view
  12. $view = $this->uri->segment(1, 'home');
  13. } else if ( $this->uri->segment(3) == false ) {
  14. // If there's no third segment in the URL then use the first two segments to find the view
  15. $view = $this->uri->segment(1, '').'/'.$this->uri->segment(2, '');
  16. } else {
  17. // If there's is three segments in the URL then use all three to find the view
  18. $view = $this->uri->segment(1, '').'/'.$this->uri->segment(2, '').'/'.$this->uri->segment(3, '');
  19. }
  20.  
  21. if (!file_exists( APPPATH . 'views/' . $view . EXT )){
  22. $view = "404";
  23. header("HTTP/1.0 404 Not Found");
  24. }
  25.  
  26. $this->load->view( $view, $this->_data );
  27.  
  28. }
  29. }
  30.  
  31. /* End of file home.php */
  32. /* Location: ./application/controllers/home.php */
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39. //following goes in the system/application/config/routes.php after the default and scaffolding, replace home with your default controller name
  40. $route['(.*)'] = 'home';

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.