Today I want to discuss extending the core Controller class in CodeIgniter. When developing 68KB I ran into a tricky situation where I needed to auto load several plugins, libraries, and models but they rely on the database which is not setup until the install is ran. So I had to do some outside the box thinking and some tinkering to get this working. But in the end it worked great and was very simple to do.
Step 1 is to create a My_controller.php file inside the libraries folder of application. Of course change “My” with your prefix setup in config.
Step 2. is to add this code to this file:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class core_Controller extends Controller
{
function __construct()
{
parent::Controller();
$this->setup();
}
// ------------------------------------------------------------------------
/**
* Setup the autoloaded items
*/
function setup()
{
if ($this->db->table_exists('sessions'))
{
$this->load->library('session');
$this->load->library('auth');
$this->load->helper('price');
$this->load->helper('image');
$this->load->helper('html');
}
else
{
redirect('setup');
}
}
}
The final step is in ALL your controllers besides the ones used in install is to extend this class. Example:
class Mycontroller extends core_Controller {
Now you can auto load anything you need and not have to rely on the default autoloader.
Be sure and read my other CodeIgniter tips!
