Skip to content

Using the Singleton Pattern

Fulvio Notarstefano edited this page Feb 26, 2020 · 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 class 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:

/**
 * Gets the main <Plugin Name> Instance. 
 * 
 * Ensures only one instance is/can be loaded.
 *
 * @see <instance global function>()
 *
 * @since <version added>
 *
 * @return \<class name>
 */
public static function instance() {

	if ( null === self::$instance ) {
		self::$instance = new self();
	}

	return self::$instance;
}

Instance global function

Add this immediately after the main class definition:

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

Instantiation or global object

Simply instantiate the plugin like so:

// fire it up!
<instance global function>();

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