How to develop WordPress-Plugins with Composer Autoloading and PHP Object-Oriented-Programming (OOP)

The most current version as of .

  1. Download and install Composer on your machine
  2. In your WordPress plugin directory, add a composer.json
    {
        "autoload": {
            "psr-4": {
                "DavidWolf\\": "app/"
            }
        }
    }
    
    Where "DavidWolf\\" references to the name of your namespace, in my case the namespace would be DavidWolf and app/ specifies, that all your class files for autoloading will be looked up in the app-directory of your plugin.
  3. Next up tell Composer to generate all required files for autoloading:
    composer install
    
  4. In your plugin .php file where your plugin header is located (/* … */) import the autoloader:
    require_once(plugin_dir_path( __FILE__ ).'vendor/autoload.php');
    
  5. To generate the autoloading mappings, Composer uses to autoload your classes, run:
    composer dump
    

PHP OOP

Just a remember, in PHP you have to declare your namespace at the begging of each file you want to use it like:

<?php

namespace DavidWolf;

defined('WPINC') or die;

// …

Wherever you want to use one of the classes from your autoloading directory use the class:

<?php

namespace DavidWolf;

use DavidWolf\Life;

defined('WPINC') or die;

$life = new Life();

// …

Also make sure your class files are named with the exact same class name as the included class (case sensitive on unix systems).

app/Life.php
— David Wolf