Skip to content

Using the Singleton Pattern

Max Rice edited this page Feb 3, 2015 · 5 revisions

Every plugin that uses the framework should conform to the singleton pattern for the main plugin class. This consists of 4 parts in the main plugin file:

Class instance

Add this after the version constant:

/** @var <class name> single instance of this plugin */
protected static $instance;

Instance method

Add this as the first helper method:

/**
 * Main Amazon Simple Pay Instance, ensures only one instance is/can be loaded
 *
 * @since <version added>
 * @see <instance global function>()
 * @return <class name>
 */
public static function instance() {
	if ( is_null( self::$instance ) ) {
		self::$instance = new self();
	}
	return self::$instance;
}

Instance global function

Add this immediately after the main class definition:

/**
 * Returns the One True Instance of <plugin>
 *
 * @since <version added>
 * @return <class name>
 */
function wc_plugin_name() {
	return <class name>::instance();
}

Instantiation or global object

Plugins created after WooCommerce 2.3 do not require a global object for backwards compatibility, simply instantiate the plugin like so:

// fire it up!
wc_plugin_name();

Plugins created prior to WooCommerce 2.3 require a global object for backwards compatibility, which will eventually be removed at a later date:

/**
 * The <class name> global object, exists only for backwards compat
 *
 * @deprecated <version singleton was added>
 * @name $<class name>
 * @global <class name> $GLOBALS['<class name>']
 */
$GLOBALS['<class name>'] = <instance global function>();

For reference, the conversion to the singleton pattern was discussed in skyverge/wc-plugins#481