CodeIgniter controllers

File 'application/controllers/gallery.php':

<?php
class Gallery extends CI_Controller {
	function index() { // default method - url site.com/gallery/ will output 'index method' (same as site.com/gallery/index)
		echo 'index method';
	}
	public function listing() { // url site.com/gallery/listing/ will output 'listing method'
		echo 'listing method';
	}
}
?>

Passing URI segments to your functions

<?php
class Gallery extends CI_Controller {
	public function listing( $category, $id ) { // url site.com/gallery/listing/landscape/777/ will output 'cat=landscape id=777'
		echo 'cat='.$category.' id='.$id;
	}
}
?>

Private functions

<?php
class Gallery extends CI_Controller {
	public function _private() { // url site.com/gallery/_private/ will not work
		// code
	}
}
?>

CodeIgniter default controller

To set the default controller, open your 'application/config/routes.php' file and set 'default_controller' variable:

<?php
$route['default_controller'] = 'Gallery';
?>

Organizing controllers into sub-folders

Create folder 'application/controllers/subfolder/' and place file with controller class into it.
To call the controller 'application/controllers/subfolder/gallery.php' your URL will look like this: 'site.com/subfolder/gallery/'

Class constructors

Constructors are useful if you need to run some code each time when the class is instantiated.

<?php
class Gallery extends CI_Controller {
       public function __construct() {
            parent::__construct();
            // this code will be executed each time when class will be instantiated (for each method of the class)
            $this->load->model( 'post_model' ); // load Post model in every function of this class
       }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *