Improve WordPress Theme and Plugin Development Using Design Patterns

Zlepšite vývoj WordPress tém a pluginov za použitia návrhových vzorov
» Improve WordPress Theme and Plugin Development Using Design Patterns

Do you want to create cleaner, more maintainable code, that is lot easier to change and build on in the WordPress environment? Giving some attention to concept of design patterns could make a massive difference here. If usage of design patterns is executed correctly during the development it can save you some time too.

What Are Design Patterns?

Design patterns help us to build our software (obviously including WordPress plugins and themes) on the knowledge of others before us. We don’t have to reinvent the wheel for solving some common problems that happened to many developers before us and we can focus on the specifics of our problem domain and customer requirements. 

Design pattern is repeatable solution to commonly reoccurring problem in the software design. It cannot be used directly, but it provides us with template for solving the problem that can be reused in many similar situations.

Studying design patterns and applying them when creating new code can drastically improve the structure and overall functionality and scalability

After studying them you can also try to refactor your older code using design patterns and you will see how much more managable code could be.

Demystifying the Design Patterns Using Hooks

Let’s start with something most of the WordPress developers are already familiar with and these are hooks, more specifically the actions and filters that are used in the WordPress a lot. 

This is specific implementation of something called publisher-subscriber(pub-sub) pattern. In this pattern we define publishers, subscribers and a message broker:

The publisher publishes a specific event, in our case by executing do_action or apply_filters.

Subscribers can subscibe to specific events by calling add_action or add_filter and execute an action when the event they are subscribed occurs.

Message broker, in our case WordPress core make sure that all of the subscribers  are notified about the publishers events they are subscribed to.

Benefits of Publisher-Subscriber (pub-sub) Pattern

This gives us a lot of benefits. Publisher does not need to know anything about its subscriber and also subscribers does not need to know anything about publisher, as long as they can react to occurring event. Even if we deactivate the plugin that creates events or consumes the events, this will cause no errors

I think that it is very useful not just consume hooks from WordPress core or plugins but also create hooks in our code and build our code around them. You are not just going to make other developers life easier if they decide to build on your plugin or theme functionality but trust me your life will also be much easier when implementing new functionality to your plugin or theme.

There are many other smart design patterns that can be used in WordPress. They mostly require a bit more work to be applied then the hooks, but they can make a huge difference in design of your plugin or theme. Great example of the design pattern that can be used in the context of WordPress is singleton pattern.

Singleton Pattern

This pattern requires knowledge of object-oriented programing. If you are not familiar with that, please study that first, and then you could come back.

Singleton pattern restricts initiation of certain class, so only one instance of the class can be created. This can be achieved by creating the private constructor, static property to store the instance and static function getInstance().This functions responsibility is to instantiate the object if it is not already instantiated and stored in the variable $instance. You can see the example down bellow

class SingletonClass
{
    private static $instance = null;

    private function __construct() {}

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

Every time some code tries to create new instance of this class, error is triggered, because the constructor is private (this better be documented to avoid confusion), so the only way to get the instance is trough our getInstance() function

Example usage for this would be to create a base class that responsibility is to instantiate all of our plugin functionality. We can bound for example configuration data to this instance, so this is accessible from anywhere in the plugin and it does not need to be fetched from database or config file multiple times, only on the single instantiation of this class.

Don’t Overuse Singleton Pattern

I think this pattern is a good example partially because it can be very tempting to overuse it, as it is easy to see the benefits of using it in many situations. I am not saying it should not be used but you have to consider drawbacks of the pattern too before using it. 

Main drawback of this pattern, in my opinion, is that every time we use this pattern we bound our functionality to direct knowledge about the singleton class. This is creating coupling of code and could cause that if we decide to change something in the singleton, we have to make many changes trough the project. 

So always think with caution before using this pattern or any other pattern, but if you are going to do a good job, this is going to be very rewarding to you.

More Patterns

We have described two design patterns in this article. These patterns can be used in many situations during the WordPress development and could improve your code and thinking. 

But this is just a very small showcase of what could be done thanks to the concept of design patterns. There is a lot more design patterns out there that could be applied during the development. Studying them and applying them could make a huge difference during the development and could have very positive impact on what you are developing. 

I encourage you to give this a try either using well-known and high-quality literature such as Design Patterns: Elements of Reusable Object-Oriented Softwareor Head First Design Patterns or on the websites such as refactoring.guru, where a lot of patterns are well described including examples in PHP.