Skip to content

Instantly share code, notes, and snippets.

@mhull mhull/.Acme-Plugin.php
Last active Aug 11, 2016

Embed
What would you like to do?
A WordPress plugin example using PHP namespaces and autoloading
<?php
#! /acme-plugin/acme-plugin.php
/**
* Plugin Name: ACME Plugin
* Description: A WordPress plugin example using PHP namespaces and autoloading
* Version: 0.0.0
* Author: Michael Hull
* Author URI: https://resoundingechoes.net
*/
namespace Acme;
require_once __DIR__ . '/autoload.php';
use Acme\Plugin;
function plugin() {
return Plugin::get_instance();
}
add_action( 'plugins_loaded', array( plugin(), 'plugins_loaded' ) );
<?php
#! /acme-plugin/src/plugin.php
/**
* The main plugin class
*/
namespace Acme;
class Plugin() {
# the singleton instance of this class
protected static $instance = null;
# get/set the singleton instance
public static function get_instance() {
if( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
# callback for WP `plugins_loaded` hook (where we can bootstrap the plugin)
public function plugins_loaded() {
// ... do stuff here ...
}
}
<?php
#! /acme-plugin/autoload.php
/**
* Autoload classes within the namespace `Acme`
*
* Basic usage is to require `src/foo/baz.php` when instantiating the class
* `Baz` within the namespace `Acme\Foo`
*/
spl_autoload_register( function( $class ) {
# project-specific namespace prefix
$prefix = 'Acme\\';
/**
* Does the class being called use the namespace prefix?
*
* - Compare the first {$len} characters of the class name against our prefix
* - If no match, move to the next registered autoloader
*/
# character length of our prefix
$len = strlen( $prefix );
# if the first {$len} characters don't match
if ( strncmp( $prefix, $class, $len ) !== 0 ) {
return;
}
# base directory where our class files and folders live
$base_dir = __DIR__ . '/src/';
/**
* Perform normalizing operations on the requested class string
*
* - Remove the prefix from the class name (so that Acme\Plugin looks at src/plugin.php)
* - Replace namespace separators with directory separators in the class name
* - Prepend the base directory
* - Append with .php
* - Convert to lower case
*/
$class_name = str_replace( $prefix, '', $class );
$possible_file = strtolower( $base_dir . str_replace('\\', '/', $class_name ) . '.php' );
# require the file if it exists
if( file_exists( $possible_file ) ) {
require $possible_file;
}
}); # end: spl_autoload_register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.