PHP Composer in WordPress Development

Composer in WordPress plugins and themes

Composer is the dependency manager of PHP. WordPress core does not use it, but in your own plugins and themes it saves copying libraries by hand: composer require downloads a library with its dependencies, and one autoloader loads all classes, the libraries’ and your own.

Problem: A plugin needs a third-party PHP library, and copying its files into the repository and including them one by one is messy.

Solution: Add a composer.json to the plugin, install libraries with composer require, load vendor/autoload.php in the main plugin file, and autoload your own classes with PSR-4.

Setting up composer.json

cd wp-content/plugins/my-plugin
composer init --no-interaction --name="myvendor/my-plugin" --type=wordpress-plugin

# a library for the plugin
composer require guzzlehttp/guzzle:^6.3

# tools only for development
composer require --dev phpunit/phpunit:^7.5
composer require --dev wp-coding-standards/wpcs

Dev dependencies are not needed on the live site: build the release with composer install --no-dev --optimize-autoloader.

Loading the autoloader

<?php
/**
 * Plugin Name: My Plugin
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
    add_action( 'admin_notices', function () {
        echo '<div class="notice notice-error"><p>My Plugin: run <code>composer install</code>.</p></div>';
    } );
    return;
}

require_once __DIR__ . '/vendor/autoload.php';

function my_plugin_fetch_data() {
    $client   = new GuzzleHttp\Client( array( 'timeout' => 10 ) );
    $response = $client->get( 'https://api.example.com/data' );

    return json_decode( (string) $response->getBody(), true );
}

Call such a function when it is needed (on a cron event, in an AJAX handler), not on every page load.

Your own classes with PSR-4

In composer.json (in JSON a backslash is escaped, so the namespace ends with \\):

{
    "autoload": {
        "psr-4": {
            "MyPlugin\\": "src/"
        }
    }
}

Now MyPlugin\Admin\Settings is loaded from src/Admin/Settings.php without any require. After changing the autoload section, regenerate the autoloader:

composer dump-autoload -o

Git and deployment

Add the vendor folder to .gitignore:

/vendor/

and commit composer.lock, so every environment installs exactly the same versions. The live site then needs vendor/ too: either run composer install --no-dev during deployment, or include vendor/ in the release zip of the plugin.

NOTE: All plugins share one PHP process. If two plugins bundle different versions of the same library, the one loaded first wins, and the other plugin may break with “call to undefined method”. For plugins you distribute, keep dependencies few, or prefix their namespaces with a tool such as PHP-Scoper.