Composer Autoloading within WordPress Plugin

A good way to begin using object oriented PHP classes is by writing everything in a single .php file. That’s completely fine for small WordPress projects. For large projects a single file quickly becomes a disorganized mess. I know from experience building CaptainCore. 🧐

Take a peak at this one gigantic PHP file before I broke it apart class-captaincore-db.php. That was my starting point. Here is how I broke that apart into organized files and introduced Composer into my workflow to automatically load them within the WordPress plugin.

📖 Pro TIP: If you just want to learn this for yourself, I’d highly recommend going through Laracasts: Object-Oriented Bootcamp video series.

Leverage Composer for autoloading.

Breaking up a single .php file into many .php files introduces the need to then require all of those new files manually from the main file. Who wants to spend time managing that? Let’s autoload the files! With Composer we can do just that.

First create a new folder within the WordPress plugin to store all of these new files. I put them under app/ however it can go wherever you wish. Next, place each PHP class into its own PHP file. These files will each need the PHP namespace declared at the top of the document. With that done my CaptainCore plugin now looks like the following.

New separated PHP classes
Individual PHP class

Install Composer and add a composer.json.

At the root of the WordPress plugin add a composer.json file and define which autoloading format you wish to follow. The PHP namespace and path name are defined like so. The “\\” simply escaping the single “\” in JSON.

{
    "autoload": {
        "psr-4": {
            "CaptainCore\\": "app/"
        }
    }
}

Next from the command line run composer install which will generate an autoload file. Add this to the main WordPress plugin file with the following code.

require plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';

Next from the command line run composer dumpautoload -o which does a big of magic and generates the proper mappings to all found classes. Now whenever PHP classes are added or removed from the app/ folder we simply need to rerun composer dumpautoload -o once and it will generate the proper file mappings.

Peak at how Composer handles the autoload.