Anfragen

PSR-4 autoloading in plugins and themes

WordPress plugins can be as simple as a few functions, but they are more often very complex. This usually leads to a lot of require paths that you need to maintain. But file path strings will be very tricky for future code refactoring. So what if we could skip writing these require paths manually and instead benefit from a technique that does all the require path lines for us? That’s exactly what a PSR-4 autoloader can do for us.


PSR-4 is a specification for how to structure your PHP files into folders that reflect your namespace and class names. If you follow this specification, you only need to write one single require path and everything else will be done for you. We will use composer to generate an autoloader that respects these specifications.

It is important to note that this only works with classes. If you prefer functional php programming there’s nothing to win for you here.

As of this point, I assume you have composer installed on your development environment. Instructions on how to install composer can be found here: https://getcomposer.org/download/

Autoload your plugins classes

First create a classes directory and a composer.json file with the following content in your plugin directory.

{
  "autoload": {
      "psr-4": {
          "MyNamespace\\": "classes"
      }
  }
}

With this configuration, we use the top-level namespace MyNamespace as the namespace prefix for every php file in the classes directory.

Some more information on how and why to use namespace in your plugins and themes: Use namespace in plugins and themes

PSR-4 — Fully qualified class names and their corresponding file paths

Open the directory of your plugin in a terminal and run composer dump-autoload. This will generate a vendor folder in your plugins directory that contains an autoload.php file. Add require_once dirname(FILE)."/vendor/autoload.php"; to your main plugin php file and after this line of code you can use all classes in your classes directory that follows the PSR-4 specification rules without any additional require path line of code 🎉.

You can do exactly the same in your theme’s function.php file.


We use this PSR-4 autoloading pattern for example with BlockX and almost all other plugins.


ADS for Plugin and Theme starterkit