editor-experiments icon indicating copy to clipboard operation
editor-experiments copied to clipboard

Expose Editor_Experiments instance as a global

Open gcorne opened this issue 11 years ago • 3 comments

Rather than

new Editor_Experiments();

it is a little bit more friendly for other developers if you do

$editor_experiments = new Editor_Experiments();

Doing so makes it easy for another plugin author to remove your action/filter and add their own variation should they want to adjust the behavior a bit.

gcorne avatar Aug 05 '14 18:08 gcorne

Or, rather than introducing a new global, you could add a static method like Editor_Expiriments::instance() that would just return $this.

JDGrimes avatar Aug 05 '14 18:08 JDGrimes

Sure. So what's the best way?

ellatrix avatar Aug 14 '14 19:08 ellatrix

The singleton approach might be a little cleaner. The drawback of singletons is that they are harder to write unit tests against, but they do avoid adding any additional global variables.

If you go with the singleton, I think the following makes sense:


private function __construct() {}
static function getInstance() {
    if ( ! self::$instance ) {
        self::$instance = new Editor_Experiments();
    }
    return self::$instance
}

And then move the statements currently in __construct() to a new init() method. To initialize, you would do something like:

Editor_Experiments::getInstance()->init();

And if another dev wanted to remove an action, they would do something like:

$instance = Editor_Experiments::getInstance();
remove_action( 'admin_enqueue_scripts', array( $instance, 'admin_enqueue_scripts' ) );

Looking through the actions and filters you're adding, I am not sure when a developer might want to do something like that, but it is a good practice to provide a way for other developers to remove hooks you're adding.

gcorne avatar Aug 14 '14 21:08 gcorne