Skip to content
This repository has been archived by the owner on Jan 19, 2021. It is now read-only.

Expose Editor_Experiments instance as a global #15

Open
gcorne opened this issue Aug 5, 2014 · 3 comments
Open

Expose Editor_Experiments instance as a global #15

gcorne opened this issue Aug 5, 2014 · 3 comments

Comments

@gcorne
Copy link

gcorne commented Aug 5, 2014

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.

@JDGrimes
Copy link

JDGrimes commented Aug 5, 2014

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

@ellatrix
Copy link
Owner

Sure. So what's the best way?

@gcorne
Copy link
Author

gcorne commented Aug 14, 2014

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants