Saturday, May 21st, 2022

Build a Simple PSR-4 Compliant Autoloader for Any Plugin

A lot of PHP developers involved in WordPress projects, especially developing plugins, opt to use Composer. Not only to require libraries they can use, but also to autoload classes and even files inside plugins.

However, some people prefer to stay away from Composer when working with WP coding. Never mind, if this is your case, you can still come up with a simple autoloading solution, without using any external libraries or scripts.

What is PSR-4 Compliance

All PSRs are coding standards, special patterns that are widely accepted by PHP developers as part of best practices. So, when we say that an autoloading script is PSR-4 compliant, we mean that it follows the requirements suggested by the 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 the same thing: it registers a callback, in which the coder will autoload all the classes in the file structure. However, if we think about the simplest case, such a callback can be an anonymous function.

And, in particular, in the case of PSR-4, the autoloading function will look for classes in a specific folder, with the namespace matching that previously declared as a prefix. Why? Because the autoloader will first look for the fully qualified class name – and that includes the corresponding namespaces. But, as a first step, let’s add to the plugin main file:

/**
 * Simple autoloading system
 *
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) 
{
});

Steps for Callback

Looks simple? Yes, it’s simple. Now, we need to follow a few steps to ensure that the correct classes are found and loaded by the script:

  1. We want to declare the plugin namespace and the directory of the classes
  2. We need to make sure that all loaded classes will have the correct namespace
  3. we only want relative class name, without namespace
  4. We reassemble the parts to find the class file name and path
  5. Finally, if that file exists, we’ll need

The spl_autoload system will perform iterations to find and load all the classes that match the requirements we have established, so let’s put all those objects inside an 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 use composer or create an autoloading class. However, this simple script keeps you from making mistakes by typing dozens of include or require already, and turns your plugin code into something cleaner and easier to update and enhance in the future.

Source link