For those of you who have been following development of the WordPress Plugin Boilerplate, you’ll recall that I previously included the `register_activation_hook` and `register_deactivation_hook` calls within the the class itself.

In the latest version of the Boilerplate, they’ve been removed outside of the context of the class and into a separate file. Last week, I received a great comment asking why this decision was made:

I have this one question – why plugin activation/deactivation hooks are registered outside the constructor (as they were in v1.0) ?

I thought it would be better to discuss the decision in a blog post rather than in a lengthy comment.

The WordPress Register Activation Hook Function

There are two ways that I can go about explaining my particular implementation.

TL;DR

I’m handling the activation and deactivation hooks outside of the plugin class because I’ve opted to implement the Singleton Pattern, which requires a different strategy.

The Long Version

First, according to the Codex, the `register_activation_hook` is meant to provide the following functionality:

The register_activation_hook function registers a plugin function to be run when the plugin is activated.

And the `register_deactivation_hook` is meant to provide similar functionality:

The function register_deactivation_hook (introduced in WordPress 2.0) registers a plugin function to be run when the plugin is deactivated.

Sure, it’s easy enough to understand – but there are some subtle nuances that come with working with these two functions.

Primarily, they expect that the functions are marked as static and their use depends on if you’re using object-oriented programming or procedural programming.

Yes, it’s completely possible – and acceptable – to keep the plugin activation and deactivation functions within the class, and it’s possible to specify the hooks in the constructor; however, because the second version of the Boilerplate places the class in a separate file, because the Boilerplate implements the Singleton Pattern, and because I’m using a secondary file to grab an instance of the plugin, I opted to place the register activation and deactivation hooks out of the constructor.

Straight from the Codex, here’s their example::

class MyPlugin {
     static function install() {
            // do not generate any output here
     }
}
register_activation_hook( __FILE__, array('MyPlugin', 'install') );

But there’s a subtly to this example and the Boilerplate and that’s that the plugin class is in one file, and the plugin is loaded by a secondary file.

To that end, I’m following the strategy above except I’ve placed the call to `register_activation_hook` in a separate file that invokes the static activation (or deactivation) functions.

So, ultimately, it’s not an arbitrary design decision. Instead, it’s more of a function of the implementation of the Singleton Pattern which is better covered in the topic of a series of different posts.