Using PSR-4 Autoloading in WordPress Plugins

Published 26th February 2015

For a while now PHP-FIG has been making the PHP world better by defining standards for things like coding standards, coding styles, loggers and, importantly, autoloading. Autoloading is important because it allows us to write our code using Namespaces which makes for a much nicer folder structure and more modular classes (and packages), without having to worry about require(ing) files all the time. If you’re still not with me have a look at the PSR-4 spec.

Anyway, I would recommend that any PHP developer worth their salt should be using PSR-0 and PSR-4 as much as possbile. So how do you go about doing this in WordPress plugins? Well it’s actually relatively simple.

Let’s say we have a WordPress plugin called “Turnover”, with a basic folder structure that looks like:

/turnover - turnover.php

So the content of our main turnover.php plugin file should look like this:

<?php /* Plugin Name: Turnover Plugin URI: http://example.com Description: Do something useful Version: 1.0.0 Author: Dev7studios Author URI: http://dev7studios.com License: GPL2 */ spl_autoload_register( 'turnover_autoload' ); function turnover_autoload($class) { $prefix = 'Dev7studios\Turnover\'; $base_dir = __DIR__ . '/src/'; $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { return; } $relative_class = substr($class, $len); $file = $base_dir . str_replace('\', '/', $relative_class) . '.php'; if (file_exists($file)) { require_once $file; } } new Dev7studiosTurnoverTurnover();

You don’t have to worry too much about what the code does, suffice to say it will autoload anything in the /turnover/src folder using the namespace prefix Dev7studiosTurnover (note this code is based on this example). You can see at the bottom we are instanciating our main Turnover class.

To make this work your folder structure should now look like this:

/turnover /src - Turnover.php - turnover.php

And your main Turnover.php class file should look like:

<?php namespace Dev7studiosTurnover; class Turnover { public function __construct() { } }

You can now continue creating your plugin as normal with the added benefit of being able to use namespaces and not having to manually require any files (from the /src folder anyway).