Created
July 17, 2012 15:31
-
-
Save ericmann/3130115 to your computer and use it in GitHub Desktop.
Sunrise if we architect to use a singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Here's the Sunrise class demonstrating how it would be used as a singleton. | |
* NOTE: Code is for discussion only and has not been tested. | |
*/ | |
class Sunrise { | |
static private $instance = null; | |
static public function get_instance() { | |
if ( ! isset( self::$instance ) ) { | |
self::$instance = new Sunrise(); | |
} | |
return self::$instance; | |
} | |
private $_delegates = array(); | |
function __construct() { | |
add_action( 'init', array( $this, 'init' ), 0 ); // Do this early | |
} | |
function register_delegate( $method_name, $callable ) { | |
$this->_delegates[$method_name] = $callable; | |
} | |
function __call( $method_name, $args ) { | |
$value = null; | |
if ( isset( $this->_delegates[$method_name] ) ) { | |
$value = call_user_func_array( $this->_delegates[$method_name], $args ); | |
} | |
return $value; | |
} | |
} | |
/** | |
* Here's how one of the classes we delegate to might look. | |
*/ | |
class Sunrise_Fields { | |
private $_fields = array(); | |
function register( $field_name, $args ) { | |
$this->_fields[$field_name] = new Sunrise_Field( $field_name, $args ); | |
} | |
function __construct() { | |
add_action( 'init', array( $this, 'init' ) ); | |
} | |
function init() { | |
$sunrise = Sunrise::get_instance(); | |
$sunrise->register_delegate( 'register_field', array( $this, 'register' ) ); | |
} | |
} | |
new Sunrise_Fields(); | |
/** | |
* This is how we might use it in an application plugin | |
*/ | |
$sunrise = Sunrise::get_instance(); | |
$sunrise->register_field( 'birthday', array( 'type' => 'date' ) ); | |
/** | |
* Or just: | |
*/ | |
Sunrise::get_instance()->register_field( 'birthday', array( 'type' => 'date' ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment