Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Last active December 24, 2015 03:49
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 mikeschinkel/6739395 to your computer and use it in GitHub Desktop.
Save mikeschinkel/6739395 to your computer and use it in GitHub Desktop.
Example class pattern for use in WordPress that takes the best parts of singletons and the best parts of instances and uses them together where 1+1 is greater than 2.
<?php
/**
* Class WP_Namespace_Class
*
* Allows access to the singleton class via the class name, no global or local variable required.
*/
class WP_Namespace_Class {
/**
* @var WP_Namespace_Class $_instance;
*/
private static $_instance;
/**
* Initialize
*/
static function on_load() {
/**
* This could just be the default. We could implement
* dependency injection to support subclasses of the
* instance class using a variety of means, i.e. via
* filters, set methods, etc.
*/
self::$_instance = new WP_Namespace_Class_Instance();
}
/**
* Allow access to singleton
*
* @return WP_Namespace_Class_Instance
*/
static function get_instance() {
return self::$_instance;
}
/**
* Returns 'foo'
*
* @return string
*/
function get_foo() {
return self::$_instance->get_foo();
}
/**
* Echo 'foo'
*/
function the_foo() {
self::$_instance->the_foo();
}
}
WP_Namespace_Class::on_load();
/**
* Class WP_Namespace_Class_Instance
*
* This class can be unit tested, easier to work with in a debugger,
* supports inheritance and the code just feels better w/o all the statics.
*/
class WP_Namespace_Class_Instance {
/**
*
*/
function __construct() {
add_action( 'init', array( $this, 'init' ) );
}
/**
*
*/
function init() {
// Initialize hooks and other stuff here.
}
/**
* Returns 'foo'
*
* @return string
*/
function get_foo() {
return 'foo';
}
/**
* Echo 'foo'
*/
function the_foo() {
echo $this->get_foo();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment