I am trying to walk away from the Singleton pattern when it comes to develop plugins for WordPress.
Why?
Because I have been reading in some sources (here, here, here, here ...) and came up with the conclusion that they are a bad thing. Or at least, not something one should use just because.
Why would I need a Singleton-like behavior?
Because I want to have an object with properties where multiple classes along different plugins can write and read those properties.
And I sincerely do not know how to approach this.
Can you please let me know how you would do it?
There may be different cases with different solutions, so I will suppose a real example.
Example:
A plugin called "Example Form" creates a custom form on the WordPress site.
The form is processed via a method added to the init hook by the plugin class.
public static function setup_actions_and_filters(){
$this_class = new self();
add_action('init', [$this_class, 'process_form']);
....
And while processing the form I may want to add some error or success messages to the active instance, so I can then display those messages in a theme doing somethig like:
$instance_of_PLUGINCLASS->show_errors();
But I don't have access to the "original" instance because I called a satic setup method in the main plugin file.
PLUGINCLASS::setup_actions_and_filters();
And that is why a common solution is to make the PLUGINCLASS use the Singleton pattern, which I want to avoid.
Did I come up with my own ideas?
Yes.
I thought about:
- Using the database - Horrible idea
- Using cookies - Terrible idea
- Using sessions - Not so nice
- Going from one request to the other sending GET or POST info - Vulnerable and dirty
- Using globals - I have read many times that it's not a good idea to use them
- Using WP Object Cache (see Singleton VS Object Caching)
function wp_cache_init() { $GLOBALS['wp_object_cache'] = new WP_Object_Cache(); }
;-) So.. there's no such thing as a free lunch. If you can't pass back and forth the variables you need through whoever called you then you have to use either globals or static variables on classes.