Skip to content

Instantly share code, notes, and snippets.

@DLMousey
Last active July 30, 2020 15:45
Show Gist options
  • Save DLMousey/209ddb1c0c1c59766f51769de5ce6fee to your computer and use it in GitHub Desktop.
Save DLMousey/209ddb1c0c1c59766f51769de5ce6fee to your computer and use it in GitHub Desktop.
Wordpress autoloading

Yes i know Composer is a thing,

Yes i know it's autoloader is freaking amazing,

Yes i'm well aware it would be much simpler to use the composer autoloader.

However, If you're submitting your plugin/theme to wordpress.org for review they get a bit uppity about using composer's autoloader sometimes.

It's also worth keeping in mind that not everyone running wp has shell access for interacting with composer.

Redistributing vendor directories is a pain in the backside as well, so go easy on the packages.

<?php
namespace Vendor\PackageName;
spl_autoload_register(function($class)
{
if(false !== strpos($class, 'PackageName'))
{
$parts = explode('\\', $class);
$targetFile = "";
if(count($parts) == 3)
{
$targetFile = $parts[2];
}
/**
* If we're not at the last position in the array
* append the section of the namespace with a trailing slash,
* Otherwise just add the section.
*
* This allows us to use multi-level namespaces to break out
* our classes into multiple directories.
*/
if(count($parts) > 3)
{
for($i = 2; $i <= count($parts) - 1; $i++)
{
if($i < (count($parts) - 1))
{
$targetFile .= $parts[$i] . '/';
}
else
{
$targetFile .= $parts[$i];
}
}
}
/**
* Adjust this path to where you'll be keeping your classes
*/
$basePath = __DIR__ . '/src/php/';
if(file_exists($basePath . $targetFile . '.php'))
{
include_once $basePath . $targetFile . '.php';
}
else
{
include_once $basePath . strtolower($targetFile) . '.php';
}
}
});
<?php
/*
Plugin Name: My Plugin Name
Descrpition: Does some stuff, Occasionally some things too
Version: 0.0.0
Author: Me
Author URI: https://myname.me
*/
// Require the autoloader file for sanity preservation purposes
require('autoload.php');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment