Using PHP 5’s SPL Autoloading with Code Igniter

One of the cooler features in PHP 5 is the SPL autoloading capability, which allows dynamic loading of classes without you having to “include” or “require” each specific one. Simply tell PHP where your class files will be loaded and a naming convention for the filenames.

Code Igniter is PHP 4 friendly and uses antiquated class/model code as a result. To modernize Code Igniter in this regard, you can use my SPL autoload helper.

Filename: spl_autoload_helper.php

<?php
/**
 * SPL Autoload Helper
 * Elliott Brueggeman
 * http://www.ebrueggeman.com
 */
 
/*** nullify any existing autoloads ***/
spl_autoload_register(null, false);
 
/*** specify extensions that may be loaded ***/
spl_autoload_extensions('.php, .class.php');
 
/*** class Loader ***/
function classLoader($class) 
{
	$filename = strtolower($class) . '.class.php';
	$file ='system/application/models/' . $filename;
	if (!file_exists($file)) 
	{
		return false;
	}
	include $file;
}
 
 
/*** register the loader functions ***/
spl_autoload_register('classLoader');
 
 
/* End of file spl_autoload_helper.php */
/* Location: ./system/application/helpers/spl_autoload_helper.php */

Within your system/application/config/autoload.php config file, add spl_autoload to your helpers so it’ll be loaded on every page.

$autoload['helper'] = array('spl_autoload');

Now when naming your model (class) files, name them foo.class.php where foo is the name of your class and put them into the standard Code Igniter system/application/models/ folder.