You may have heard that adding actions or filters to your WordPress class constructor is not a good idea when creating a theme or plugin. Yes?
Quick side note! Isn’t it annoying when someone mentions something isn’t a good idea, but doesn’t explain why? Yea I think so too.
So let me explain why and attempt to do it in a way that makes sense.
Essentially, there are two reasons why.
Why not to add actions and filters to your WordPress class constructor
- The role of the constructor
- Makes your unit testing, less unit-ty.
So first, the role of the constructor in PHP is to initialize your object’s properties. Everything else should be handled in the class methods. Is adding actions initializing the object? No it’s not since the actions (or filters for that matter), don’t do any initializing, they only hook in to WordPress and get called later during the WordPress execution.
Makes sense? No? Have a read of Carl Alexander’s article on plugin constructors – he has a knack of explaining things simply.
And the second reason, less unit-ty unit tests, probably isn’t so self explanatory. A unit test is meant to run in isolation and test the smallest unit of code. Most WordPress unit tests I’ve seen (and am guilty of writing) are actually more like integration tests as they test WordPress features and not class methods/units of code.
So if we’re writing pure unit tests, in the way they are intended to be written, and we add actions and filters to a constructor of a class in our plugin or theme, then we can’t test our code (or instantiate an object of a class), without WordPress and all the action/filters being applied. Yes, sometimes you may want them to be applied, but by only applying them in a separate method, you have the choice to load them if you want to by calling a method.
And if that didn’t make sense, check out Tom McFarlin’s article on the issue.
Now that all is said and done, I hope you have a better understanding of why you shouldn’t use actions and filters in your WordPress theme or plugin class constructors. Got questions? Hit me up in the comments below.