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:

Autoload your plugins classes

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

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:

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 ( )



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store