Skip to content

Instantly share code, notes, and snippets.

@chaance
Last active April 17, 2018 21:52
Show Gist options
  • Save chaance/601c248904ee022b8609f0dce6f561c9 to your computer and use it in GitHub Desktop.
Save chaance/601c248904ee022b8609f0dce6f561c9 to your computer and use it in GitHub Desktop.
wp-class-autoloader
<?php
if ( ! defined( 'WPINC' ) ) {
die;
}
/**
* Class autoloader
*
* @param string $class Qualified class name.
*/
function xx_class_autoloader( $class ) {
// If the $class_name does not include our theme's namespace, GTFO.
if ( false === strpos( $class, 'Theme_Name' ) ) {
return;
}
$namespace_parts = explode( '\\', $class );
// Format parts to match filenames.
$file_parts = array_map( function( $part ) {
return str_replace( '_', '-', strtolower( $part ) );
}, $namespace_parts );
$class_path = get_template_directory() . '/inc/classes/';
// If class uses sub-namespaces, we'll stick them in matching sub-directories.
if ( count( $file_parts ) > 2 ) {
// Remove first array item (theme namespace) and last array item (filename).
// Anything in between will go in the path.
$class_path .= implode( DIRECTORY_SEPARATOR, array_slice( $file_parts, 1, count( $file_parts ) - 2 ) ) . '/';
}
// Construct file path + name.
$file = $class_path . 'class-' . end( $file_parts ) . '.php';
if ( file_exists( $file ) ) {
require_once $file;
} else {
echo "GTFO: `{$file}` does not exist.<br />";
}
}
spl_autoload_register( 'xx_name_autoloader' );
@chaance
Copy link
Author

chaance commented Nov 7, 2017

This autoloader looks for class files stored in the theme directory inc/classes that are properly namespaced using Theme_Name, and sotring classes with sub-namespaces in subdirectories.

Example: Theme_Name\Display_Classes\Render_Content would be loaded from inc/classes/display-classes/class-render-content.php.

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