Home > Development | General > PHP class autoloader

PHP class autoloader

I have been working on a version of the PHP class autoloader. I have a config file that sets up the path information for the program. Generally you would want to include the config and the includes file in the entry point of the program.

Content of config.php

define('ROOT_PATH', dirname(dirname(dirname(__FILE__))));
define('APP_DIR', basename(dirname(dirname(__FILE__))));

Content of include.php

// Manually require this so that the AutoLoader can use it.
require_once('classes/string_tools.php');
 
/**
 * Autoloads classes
 *
 * All classes must be CamelCased in a filename that is under_barred.php
 *
 * Requires: StringTools::camelToUnderbar()
 *
 * @param string $className
 */
function autoload($className)
{
    /*
     * Register the paths that we will look in.
     *
     * TODO this should probably be done dynamically
     */
    $paths = array(
        'classes/',
        'classes/analyzers/'
    );
 
    foreach ($paths as $path)
    {
        $p = ROOT_PATH . '/' . APP_DIR . '/' . $path . StringTools::camelToUnderbar($className) . '.php';
        /*
         * Attempt to include the file from the path and suppress any errors with "@"
         */
        if (file_exists($p))
        {
            if (include_once($p))
            {
                break;
            }
        }
    }
}
 
spl_autoload_register('autoload');

You will notice this has a requirement for the StringTools class. I got these functions from here and wrapped them in a class.

Content of string_tools.php

/**
 * General string tools
 */
class StringTools
{
 
    /**
     * Convert MyClass to my_class
     *
     * @param string $class_name
     */
    public static function camelToUnderbar($str)
    {
        /*
         * Find all upper case chars except the first one and insert an underbar
         * then lower case the entire string.
         */
        $str[0] = strtolower($str[0]);
        $func = create_function('$c', 'return "_" . strtolower($c[1]);');
        return preg_replace_callback('/([A-Z])/', $func, $str);
    }
    /**
     * Convert my_class to MyClass or myClass
     *
     * @param string $str
     * @param string $capitalise_first_char
     * @return string
     */
    public static function toCamelCase($str, $capitalise_first_char = false)
    {
        if ($capitalise_first_char)
        {
            $str[0] = strtoupper($str[0]);
        }
        $func = create_function('$c', 'return strtoupper($c[1]);');
        return preg_replace_callback('/_([a-z])/', $func, $str);
    }
 
}

Comments are closed.

TOP