-
Notifications
You must be signed in to change notification settings - Fork 42
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:
Add this after the version constant:
/** @var <class name> single instance of this plugin */
protected static $instance;
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;
}
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();
}
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
- Home
- General Usage
- Payment Gateways
- WooCommerce Blocks
- Updating
- Testing
- Workflow