Autoloader for WordPress

The process of creating an autoloader for WordPress is a bit problematic. The WordPress core doesn’t use autoloaders, so when you register one via spl_autoload_register(), the autoloader you define in your plugin or theme, will take control of how the WordPress core loads its internal classes.

Other 3rd-party plugins may also break if your autoloader function tries to load their classes in your namespace/source-path.

However, if you put all your classes into your own unique namespace (as is best practice in most other languages), you shouldn’t have any problems in avoiding invocations where your autoload function tries to load classes not from your distribution.

Here I put all my own classes in a namespace called ‘supervillain’, using a plugin structure as pictured here:

Screen Shot 2013-04-10 at 11.42.38

The SoundcloudPlayer-plugin.php file will be included by WordPress. In there I require_once the bootstrap.php, containing this code:

<?php
function load($className){
    if(false!==stripos($className, 'supervillainhq')){
        require str_replace("\\", '/', dirname(__FILE__) .'/'. __NAMESPACE__ . $className . '.php');
    }
}

spl_autoload_register(__NAMESPACE__."\\load");
?>

Further down in Soundcloudplayer-plugin.php I can create an instance of the SoundcloudPlayer class, defined in SoundcloudPlayer.php like this:

$scplayer = new supervillainhq\SoundcloudPlayer();

The SoundcloudPlayer class is defined like this:

<?php
namespace supervillainhq{
    class SoundcloudPlayer extends WordPressPlugin{
        public function test(){
            return "test";
        }
    }
}
?>

Of course, this still needs testing

Leave a comment