Class constructors should only setup the object

It’s common practice in the larger PHP world, but something the WordPress ecosystem has yet to catch up on. All too often, I see WordPress plugins and themes setup actions, filters and use other WordPress specific functions in class constructors. This leads to a class that is directly coupled to WordPress logic.

What I recommend instead, is to create a separate method that sets up the object in a WordPress specific way. In this method, which I usually name setup(), you setup actions, filters and other WordPress specific function calls:

This method needs to be called separately when you instantiate the object in your own logic and this can feel like extra work. The benefits of doing it in a separate method are much larger though; you can now easily unit test the class, without having to mock all of the WordPress functions you use. In unit tests, you now instantiate the object, but don’t call the setup() method, so your tests can run independently of the WordPress core.