Skip to content

Instantly share code, notes, and snippets.

@pixelbart
Last active June 15, 2020 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelbart/57a602116edc4cffd1157744cfb1fa21 to your computer and use it in GitHub Desktop.
Save pixelbart/57a602116edc4cffd1157744cfb1fa21 to your computer and use it in GitHub Desktop.
WordPress Plugin: A plugin which includes or autoloads classes with namespaces.
<?php
/**
* An example class in the subfolder: core/modules/core.php
*/
namespace NAMESPACE\Core\Modules;
class My_Class
{
/**
* Saves an instance of the class.
*
* @var Core
*/
private static $instance;
/**
* Creates an instance of the class if it does not yet exist.
*
* @return Core
*/
public static function get_instance()
{
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
public function __construct()
{
}
}
<?php
/**
* Plugin Name: My Plugin
* Description: A plugin which includes or autoloads classes with namespaces.
* Version: 1.0.0
* Author: Pixelbart
* Author URI: https://pixelbart.de
*/
if ( ! defined( 'ABSPATH' ) ) {
die();
}
define( 'PLUGIN_FILE', __FILE__ );
define( 'PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
add_action( 'plugins_loaded', array( 'My_Plugin', 'get_instance' ) );
if ( ! class_exists( 'My_Plugin' ) ) {
class My_Plugin
{
/**
* Class prefix.
*
* @var string
*/
private $prefix = 'NAMESPACE\\';
/**
* Saves an instance of the class.
*
* @var My_Plugin
*/
private static $instance;
/**
* Creates an instance of the class if it does not yet exist.
*
* @return My_Plugin
*/
public static function get_instance()
{
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor.
*
* @return void
*/
private function __construct()
{
spl_autoload_register( array( $this, 'autoload' ) );
$this->init();
}
/**
* Includes all classes.
*
* @param string $class_name The name including namespace of the class.
*
* @return void
*/
public function autoload( $class_name )
{
$prefix = $this->prefix;
$len = strlen( $prefix );
if ( 0 !== strncmp( $prefix, $class_name, $len ) ) {
return;
}
$relative_class = substr( $class_name, $len );
$path = explode( '\\', strtolower( str_replace( '_', '-', $relative_class ) ) );
$file = array_pop( $path );
$file = PLUGIN_PATH . implode( '/', $path ) . '/class-' . $file . '.php';
if ( file_exists( $file ) ) {
require $file;
}
}
/**
* Initializes the classes.
*
* @return void
*/
public function init()
{
if ( file_exists( PLUGIN_PATH . '/core/vendor/autoload.php' ) ) {
require_once PLUGIN_PATH . '/core/vendor/autoload.php';
}
$classes = [
'NAMESPACE\Core\Modules\My_Class',
];
foreach ( $classes as $class ) :
call_user_func( array( $class, 'get_instance' ) );
endforeach;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment