A lot of PHP developers involved with WordPress projects, especially those developing plugins, opt for using Composer. Not only for requiring libraries they can use, but also for autoloading classes and even files inside the plugin.
However, some prefer to keep distance from Composer when dealing with WP coding. No problem, if this is your case, you can still come up with a simple autoloading solution, without using any external library or script.
What is PSR-4 compliant
All PSR are coding standards are particular patterns widely accepted by PHP developers as being part of the best practices. So, when we say an autoloading script is PSR-4 compliant, that means it follows the requirements suggested by PSR’s maintainers – PHP-FIG.
First things first: when we talk about autoloading in PHP, we need to rely on the function spl_autoload_register(). In fact, this function does a single job: it registers a callback, in which the coder will autoload all classes in a file structure. However, if we think of the simplest situation, such callback can be an anonymous function.
And, particularly, in the case of PSR-4, the autoloading function will look for classes in a specific folder, in which the namespace matches that previously declared as the prefix. Why? Because the autoloader will firstly look for the fully qualified class name – and this includes the respective namespaces. But, as a first step, let’s add in the plugin main file:
/**
* Simple autoloading system
*
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class)
{
});
Steps for the callback
Looks simple? Yeah, it is simple. Now, we just need to follow a some steps to make sure the right classes are found and loaded by the script:
- We want to declare the plugin namespace and the classes’ directory
- We need to make sure that all loaded classes will have the right namespace
- We want just the relative class name, without the namespace
- We reassemble parts to find the class filename and path
- Finally, if that file exists, we will require it
The spl_autoload system will perform the iterations to find and load all classes that match the requirements we established, so let’s put all of those items inside the anonymous function:
spl_autoload_register(function ($class) {
// STEP 1
$prefix = 'Plugin\\Classes\\';
$baseDir = __DIR__ . '/includes/';
// STEP 2
$lenght = strlen($prefix);
if (strncmp($prefix, $class, $lenght) !== 0) {
return;
}
// STEP 3
$relativeClass = substr($class, $len);
// STEP 4
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
// STEP 5
if (file_exists($file)) {
require $file;
}
});
Personally, I still prefer to either use Composer or creating an autoloading class. However, this simple script already prevents you to make mistakes from typing dozens of includes or requires, and turns your plugin code in something cleaner and easier to update and enhance in the future.