Extending Codeigniter core classes is often useful for adding functionality or changing an existing function without altering the frameworks core code. We’ve already done this once with the router class for search engine friendly URLs and this time we’ll be doing it with the CI_Controller class so that we can set the referring controller every request although you could do anything here. E.g setting a userdata variable.
The first step is to create a file called MY_Controller.php in the application/core/ folder. Remember that capitalization is important. The file should contain the following code:
<?php
class MY_Controller extends CI_Controller {
function __construct ()
{
parent::__construct();
$this->session->set_flashdata('referrer', uri_string());
}
}
The above code stores the method and class plus any other segments in a flashdata variable called referrer.
In order to use any code you put in your MY_Controller class you need to make sure your controllers extend MY_Controller instead of CI_Controller (See the example below). The code will be ran and you can access it in the normal way.
Example Controller – Default welcome.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends MY_Controller {
public function index()
{
echo "Referrer: ".$this->session->flashdata('referrer');
echo anchor(uri_string(), 'clicky');
$this->load->view('welcome_message');
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */