Extending the Controller

CodeIgniter’s core Controller should not be changed, but a default class extension is provided for you atapp/Controllers/BaseController.php. Any new controllers you make should extend BaseController to takeadvantage of preloaded components and any additional functionality you provide:

  1. <?php namespace App\Controllers;
  2.  
  3. use CodeIgniter\Controller;
  4.  
  5. class Home extends BaseController {
  6.  
  7. }

Preloading Components

The base controller is a great place to load any helpers, models, libraries, services, etc. that you intend touse every time your project runs. Helpers should be added to the pre-defined $helpers array. For example, ifyou want the HTML and Text helpers universally available:

  1. protected $helpers = ['html', 'text'];

Any other components to load or data to process should be added to the constructor initController(). Forexample, if your project uses the Session Library heavily you may want to initiate it here:

  1. public function initController(...)
  2. {
  3. // Do Not Edit This Line
  4. parent::initController($request, $response, $logger);
  5.  
  6. $this->session = \Config\Services::session();
  7. }

Additional Methods

The base controller is not routable (system config routes it to 404 Page Not Found). As an added securitymeasure all new methods you create should be declared as protected or private and only be accessed through thecontrollers you create that extend BaseController.

Other Options

You may find that you need more than one base controller. You can create new base controllers as long as any other controllers that you make extend the correct base. For example, if your projecthas an involved public interface and a simple administrative portal you may want to extend BaseController tothe public controllers and make AdminController for any administrative controllers.

If you do not want to use the base controller you may bypass it by having your controllers extend the systemController instead:

  1. class Home extends Controller
  2. {
  3.  
  4. }