I’ve never liked how i was handling class loading in my BHAA wordpress plugins.

<?php
require_once (dirname (__FILE__) . '/../bootstrap.php');

and then has a nasty Bootstrap.php file with a load of ‘require_once()’ calls

<?php
define( 'BHAA_PLUGIN_DIR' , dirname(__FILE__) );
// admin
require_once(BHAA_PLUGIN_DIR.'/admin/class-runner-admin.php');
require_once(BHAA_PLUGIN_DIR.'/admin/class-event-admin.php');
require_once(BHAA_PLUGIN_DIR.'/admin/class-race-cpt.php');
require_once(BHAA_PLUGIN_DIR.'/admin/class-league-cpt.php');
// includes
require_once(BHAA_PLUGIN_DIR.'/includes/class-event.php');
// public
require_once(BHAA_PLUGIN_DIR.'/public/includes/class-realex.php');

I knew I could use composer to handle this.

First i added this to my composer.json file

{
  "autoload": {
    "classmap": [
      "./admin",
      "./includes",
      "./public"
    ]
  }
}

and the ran the ‘composer install’ command to re-generate by autoloader config.

This generate a php file at this path ‘./vendor/composer/autoload_classmap.php’

<?php
autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'AbstractLeague' => $baseDir . '/includes/model/class-abstract-league.php',
    'BaseModel' => $baseDir . '/includes/model/class-basemodel.php',
    'Bhaa' => $baseDir . '/public/class-bhaa.php',
    'BhaaImport' => $baseDir . '/admin/import.php'er.php',
    ...
    'WPFlashMessages' => $baseDir . '/admin/WPFlashMessages.php',
);

The final step to call the composer generated autoload.php file from my plugin, so add this line to ‘bhaawp.php’

<?php
require_once('vendor/autoload.php');

Need to remove the old bootstrap now!

Updated:

Leave a Comment