Extending CI_Controller Extending CI_Controller codeigniter codeigniter

Extending CI_Controller


The autoloader doesn't automaticly include other controllers. you will have to include it manually like this:

if (!defined('BASEPATH'))exit('No direct script access allowed');    include_once(APPPATH . 'controllers/brandnewclass.php');


If you want to create a custom base controller and make other controllers extend there, you can do it in following ways:

  1. Create MY_Controller extending CI_Controller in application/core/ folder and make other controllers extend MY_Controller as MY_Controller will be autoloaded from core (This I guess you already know but want other alternatives.

  2. Create MY_Controller in application/core/. Then create other level of Controllers that can primarily be Admin_Controller and Frontend_Controller. Now, one of these controllers will make base for your actual used controllers.

e.g. in application/core/MY_Controller.php

class MY_Controller extends CI_Controller {    public function __construct(){        parent::__construct();    }}

Then Admin and Frontend controllers will be created in application/libraries/ and will extend MY_Controller like

class Admin_Controller extends MY_Controller {    public function __construct(){        parent::__construct();    }}

Now, Any controller can extend one of these 2 controllers but for doing that you will have to autoload them. For autoloading in this case there can be a confusion because setting autoload['libraries'] in config/autoload.php will not work . That autoload works inside a controller but here we need to autoload before that i.e. in the class declaration. Will need to set this code in config/config.php

function __autoload($class) {  $path = array('libraries');  if(strpos($class, 'CI_') !== 0) {    foreach($path as $dir) {        $file = APPPATH.$dir.'/'.strtolower($class).'.php';        if (file_exists($file) && is_file($file))            @include_once($file);    }  }}

Now you can create your own controller

class newController extends Admin_Controller{}

This is the most suggested method making your structure quite clean and effective. May take some effort in understanding for the first time but is definitely worth it.

  1. Third method is just a tweak of the second one, just based on the condition you mentioned of not using MY_ControllerYou can make Admin_Controller or Frontend_Controller extend CI_Controller directly and not extend MY_ControllerThat may just lead to some duplicity of code in both these controllers if that may be the case