Business, Tech, Life, and Whatever else

Extending the core Controller in CodeIgniter

by Eric Barnes on July 7, 2009

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!

You May Also Be Interested In...

Code Igniter Template Tutorial
July 7, 2008

CodeIgniter Authorization
July 10, 2009

CodeIgniter TextMate Bundles
November 2, 2009

CodeIgniter – Change Views Location
July 6, 2009

Subscribe Now

If you enjoyed this post, you will definitely enjoy my others. Subscribe to the feed to get instantly updated for those awesome posts soon to come.


blog comments powered by Disqus