Decouple from WordPress databases by using repositories

A quick and easy way to decouple your code from WordPress logic, is by using repositories. Repositories are standardized ways to get and put data in a data store, usually databases. WordPress introduces a couple functions to interact with various database tables (get_post_meta(), get_option(), etc.) that are commonly used inside plugin and theme files, that are cumbersome to mock while testing. Repositories on the other hand are very easy to mock in unit tests.

For example, let’s have a look at this class that is designed to interact with a specific meta field of a WP_Post object:

Notice how this checkMeta() method is directly coupled to the WordPress get_post_meta() function? As soon as we want to unit test this method, we will need to mock that function, so we don’t have to load WordPress entirely just for this function.

Instead, I recommend using a repository for this kind of logic. By making the repository implement an interface, the implementation of the repository is irrelevant inside our MetaChecker class:

We can now implement the repository, by passing the interface as a required parameter in the constructor. This means that when you make a new MetaChecker object, you need to provide a repository implementing the MetaRepository interface:

This is obviously a very basic example to illustrate the best practice of using repositories. In order to effectively utilize this technique, dependency injection can be used to specify what parameters need to be passed to certain objects constructors, so you don’t need to manually provide these objects every single time.

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 *