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.

About this site

Noticed how lightning fast this website is? It's powered by a Digital Ocean VPS and they are awesome. Go check it out (and get $10 in credits for free when signing up via this link)!

Leave a Reply

Your email address will not be published. Required fields are marked *