Skip to content

Commit

Permalink
Implement CMB2_Ajax as a singleton.
Browse files Browse the repository at this point in the history
CMB2_Ajax is already being used as a singleton, but doesn't enforce it which leads to the static `hooks()` function, so let's enforce it and be done with it.
  • Loading branch information
jrfnl committed Mar 1, 2016
1 parent 895fc27 commit 73a1da8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
40 changes: 23 additions & 17 deletions includes/CMB2_Ajax.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,34 @@ class CMB2_Ajax {
protected $ajax_update = false;

/**
* Constructor
* @since 2.2.0
* Instance of this class
* @since 2.2.2
* @var object
*/
public function __construct() {
self::hooks( $this );
}
protected static $instance;

/**
* Hook in the oembed ajax handlers
* @since 2.2.0
* @param CMB2_Ajax $self This object (for hooking)
* Get the singleton instance of this class
* @since 2.2.2
* @return object
*/
public static function hooks( $self ) {
static $hooked = false;

if ( ! $hooked ) {
add_action( 'wp_ajax_cmb2_oembed_handler', array( $self, 'oembed_handler' ) );
add_action( 'wp_ajax_nopriv_cmb2_oembed_handler', array( $self, 'oembed_handler' ) );
// Need to occasionally clean stale oembed cache data from the option value.
add_action( 'cmb2_save_options-page_fields', array( __CLASS__, 'clean_stale_options_page_oembeds' ) );
$hooked = true;
public static function get_instance() {
if ( ! ( self::$instance instanceof self ) ) {
self::$instance = new self();
}

return self::$instance;
}

/**
* Constructor
* @since 2.2.0
*/
protected function __construct() {
add_action( 'wp_ajax_cmb2_oembed_handler', array( $this, 'oembed_handler' ) );
add_action( 'wp_ajax_nopriv_cmb2_oembed_handler', array( $this, 'oembed_handler' ) );
// Need to occasionally clean stale oembed cache data from the option value.
add_action( 'cmb2_save_options-page_fields', array( __CLASS__, 'clean_stale_options_page_oembeds' ) );
}

/**
Expand Down
2 changes: 1 addition & 1 deletion includes/helper-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function cmb2_utils() {
*/
function cmb2_ajax() {
static $cmb2_ajax;
$cmb2_ajax = $cmb2_ajax ? $cmb2_ajax : new CMB2_Ajax();
$cmb2_ajax = $cmb2_ajax ? $cmb2_ajax : CMB2_Ajax::get_instance();
return $cmb2_ajax;
}

Expand Down

0 comments on commit 73a1da8

Please sign in to comment.