Skip to content

Instantly share code, notes, and snippets.

@sheabunge
Last active June 27, 2023 03:35
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save sheabunge/50a9d9f8234820a989ab to your computer and use it in GitHub Desktop.
Save sheabunge/50a9d9f8234820a989ab to your computer and use it in GitHub Desktop.
Basic PHP class autoloader that follows the WordPress coding standards for class names and class filenames
<?php
namespace Shea\Example_Plugin;
/**
* Enable autoloading of plugin classes in namespace.
*
* @param $class_name
*/
function autoload( $class_name ) {
// Only autoload classes from this namespace.
if ( false === strpos( $class_name, __NAMESPACE__ ) ) {
return;
}
// Remove namespace from class name.
$class_file = str_replace( __NAMESPACE__ . '\\', '', $class_name );
// Convert class name format to file name format.
$class_file = str_replace( '_', '-', strtolower( $class_file ) );
// Convert sub-namespaces into directories.
$class_path = explode( '\\', $class_file );
$class_file = array_pop( $class_path );
$class_path = implode( '/', $class_path );
// Load the class.
require_once sprintf( '%s/php/%s/class-%s.php', __DIR__, $class_path, $class_file );
}
spl_autoload_register( __NAMESPACE__ . '\autoload' );
@szepeviktor
Copy link

@sheabunge Maybe you are interested in autoloading core classes: https://github.com/szepeviktor/wordpress-autoloaded

@arvilmena
Copy link

@sheabunge do you have example usage on where to slap this snippet?

@sheabunge
Copy link
Author

@arvilmena you could use it in the main file of a plugin or the functions.php file of a theme, before loading any of the associated classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment