Classmap autoloading for WordPress

Generating classmap based autoload for WordPress plugins and themes.

Copying from Composer

In an attempt to re-create what Composer does using a combination of the autoload directive in the composer.json file and the CLI

composer dump-autoload

command I’ve drafted a simple PHP script that create classmap based autoloaders for PHP 5.2+ projects (WordPress themes and plugins in my case).

An example

I might be working on a simple WordPress plugin with the following directory structure:


I have my classes named following the format


If I use the tad prefix for the class names the Strings.php file above defines the tad_Utils_Strings class, the Header.php file defines the tad_AjaxHandlers_Header class and so on. I’d like to have an autoload.php file, defining an SPL and PHP 5.2 compatible autoload function, that I can include in my main plugin class and tests to benefit from autoloading.

The script

I’ve pushed the script to a gist and stored its code in a dump-autoload.php file (imitating Composer because it’s easier to remember for me) and moved to the file to a folder in my executable path.
Once that’s done I am able to invoke the script from any folder; in the example file structure above I call it like this

dump-autoload --prefix='tad' --sep='_' --dir='src'

to have the autoload.php file below generated for me

function tad_autoload($class)
    $map = array(
        'tad_AjaxHandlers_Header' => '/src/AjaxHandlers/Header.php',
        'tad_AjaxHandlers_Request' => '/src/AjaxHandlers/Request.php',
        'tad_AjaxHandlers_Response' => '/src/AjaxHandlers/Response.php',
        'tad_Utils_Strings' => '/src/Utils/Strings.php',
        'tad_Base' => '/src/Base.php',
    if (isset($map[$class]) && file_exits($file = dirname(__FILE__) . DIRECTORY_SEPARATOR . $map[$class])) {
        include $file;

I just need to include this file in my main plugin classs to have a working autoloader in place. Running the script with the --help argument make it display its short documentation.