Skip to content

Commit

Permalink
Merge pull request #602 from jrfnl/feature/cmb2_ajax-is-singleton
Browse files Browse the repository at this point in the history
Implement CMB2_Ajax as a singleton.
  • Loading branch information
jtsternberg committed Mar 2, 2016
2 parents 44d21aa + f364403 commit 799e721
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 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
4 changes: 1 addition & 3 deletions includes/helper-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ function cmb2_utils() {
* @return CMB2_Ajax object CMB2 utilities class
*/
function cmb2_ajax() {
static $cmb2_ajax;
$cmb2_ajax = $cmb2_ajax ? $cmb2_ajax : new CMB2_Ajax();
return $cmb2_ajax;
return CMB2_Ajax::get_instance();
}

/**
Expand Down

0 comments on commit 799e721

Please sign in to comment.