Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From \$16.50/m

Difficulty:IntermediateLength:LongLanguages:
This post is part of a series called Object-Oriented Autoloading in WordPress.

I recently wrapped up a series in which I covered namespaces and autoloading in WordPress. If you're not familiar with either of the above terms, then I recommend checking out the series.

The gist of what you can expect to learn is as follows:

In this series, we're going to take a look at exactly what PHP namespaces are, why they are beneficial, and how to use them. Then we're going to take a look at how to use autoloaders to automatically load the files that we need without having to manually load them in our code.

While working on the series, specifically that of the autoloader, I couldn't help but recognize a number of code smells that were being introduced as I was sharing the code with you.

This isn't to say the autoloader is bad or that it doesn't work. If you've downloaded the plugin, run it, or followed along and written your own autoloader, then you know that it does in fact work.

But in a series that focuses on namespaces—something that's part and parcel of object-oriented programming—I couldn't help but feel uncomfortable leaving the autoloader in its final state at the end of the series.

Don't misread me: I still stand by the series, what was covered, and the end result of what we produced. But from an object-oriented standpoint, there's more work that can be done. So in this follow-up series, we're going to be revisiting the concept of autoloaders from the perspective of object-oriented programming.

Specifically, we're going to talk about the concept of:

• interfaces
• interface implementation
• the single-responsibility principle
• and other principles and ideas that are core to object-oriented programming

It is my hope that by the time we complete this series, we will not only have refactored our autoloader into something that's more maintainable and easier to read, but that it also adheres to greater object-oriented practices.

With that said, let's get started.

Getting Started

As with nearly every post I write, I like to try to do two things:

1. Define a roadmap of where we're going.
2. Give you everything you need to know to get your machine up and running.

Before we jump into writing any code, let's do that now.

Over the next two posts, we're going to take a look at some object-oriented concepts that are going to allow us to improve on the plugin that we built in the previous series.

If you don't have a copy of that plugin, then you can download a copy of it; however, I'll be sharing complete code examples, comments, and explanations throughout each tutorial.

The series is going to assume you know nothing about any of the concepts that we'll be discussing so we'll be starting from the ground up. All you need is to have enough software on your machine to get a copy of WordPress up and running, and an editor in which you can edit code.

What You Need

To get started, you're going to need the following tools:

After you have all of that in place (and I know it seems like a lot, but it really doesn't take long to set up), you'll need to install a copy of the plugin linked above.

Once done, we're ready to start talking about interfaces and the single responsibility principle.

Interfaces Defined

Depending on your background in software, when you hear the word "interface," you may end up thinking of what the user actually sees on the screen. You know: A user interface.

But when it comes to object-oriented design, that's not what we're talking about at all. Instead, we're talking about a class interface. And this can usually be described as the class and the public methods it exposes for other classes to communicate with it.

Is there a more formal definition? Sure. Wikipedia offers one:

In computing, an interface is a shared boundary across which two separate components of a computer system exchange information.

This isn't that bad, actually. It's general enough to apply to nearly any programming language, and it's not so technical that we can't understand it.

Then again, we're working with PHP. So what does the PHP manual have to offer on the topic?

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

In my opinion, this is a really good definition. It's simple. It's language agnostic (to my knowledge), and it works well across most (if not all) object-oriented languages. The manual even goes on to say:

Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.

These are two points that we must remember if we're going to be implementing our own interfaces, especially when it comes to this plugin. Namely, we need to remember the following:

1. We define an interface much like we do a class, but we use the interface keyword.
2. The methods that are defined in an interface have to the public (as opposed to being protected or private) because this is what guarantees the functionality other classes can access.

Before we go any further, what might an interface in a WordPress project look like? Here's an example from a project I've been working on:

The code above should be clear as to what purpose it serves, especially given the comment that sits above the interface.

As we all know, WordPress can register and enqueue two types of assets: stylesheets and JavaScript files.

Since both of these are assets, then it would stand to reason that when we create classes for stylesheet management or JavaScript management, we'd generalize it as an assets interface, right?

Furthermore, we know we want to initialize the file using an init method so that we can hook the specified enqueue function to the proper WordPress API function. Alternatively, there may be some other work you'd like to do, and if that's the case, then you may want to add another method signature to the interface.

Whatever the case may be, any class that implements this interface must provide functionality for the following methods. So what would a class that implements this interface look like?

Here's a very simple example of a class that adds stylesheets to the administration area of WordPress:

Now how this is instantiated and enforced via PHP is beyond the scope of this tutorial. We'll see it plenty when we begin refactoring our autoloader.

But the point I'm trying to show is that an interface defines the public methods a class must implement. It doesn't define the implementation, but it guarantees that a certain set of functions will exist and are publicly accessible to third-party classes.

The Single Responsibility Principle

One of the challenges of talking about the single responsibility principle is that it's often been misunderstood to mean something like:

A class (or function or routine) should do one and only one thing.

But that's a little misguided, isn't it? I mean even a simple for loop does more than one thing: It initializes a value, compares to values, and then iterates the value when the body of the loop is complete.

Instead, the principle states the following:

A class should have only one reason to change.

Because so many of us developers leverage Google to help us in our day-to-day work, I think it's important to understand the source of this idea. That is, this came from Uncle Bob Martin, as he's casually known, or Robert Martin, who has authored a number of top-shelf programming books.

The idea of a class having only one reason to change carries with it a whole host of implications, doesn't it? Here's one example that comes to mind from our autoloader as it stands today.

Let's review the code (and I know it's not a class, it's a function, but the principle is applicable):

There is a lot of stuff happening within this function. Just looking at it from a high level, we can see that it's doing the following:

• It determines if PHP is trying to invoked the code in this function.
• The function determines if we're loading an interface or a class.
• The autoloader then tries to include the file or it throws an error.

If a class is supposed to only have one reason to change, there are three reasons above (and that's just at a high level) at which this single function could change. Furthermore, the code could be clearer, as well.

I'm not one to shy away from code comments, but there's a lot of explanation happening in the code above. And it's fine when you're just getting started writing an autoloader, but when you're headed into more advanced territory such as we are, then that won't hold up to more rigorous architectures.

Bringing the Two Together

This is where interfaces and the single responsibility principle can come to work hand in hand.

Just as an interface provides a set of function signatures (or a contract) for what its implementers will provide, it can ensure that any class implementing that interface adheres strictly to what it defines.

But this raises an interesting question: Should we have multiple interfaces? And the answer is that it depends on the nature of the solution that you're trying to create.

In our case, I think it makes sense.

After all, we're looking to examine an incoming class name and determine if it's a interface or a class, or if it deserves to throw an error. Furthermore, we're looking to ensure that the proper file is included with the rest of the system.

But that's beyond the topic of this particular tutorial and one we'll have to explore in more depth when it comes time to write more code.

Conclusion

At this point, we've covered the necessary concepts so that we can begin refactoring our autoloader. That is, we'll be introducing an interface, making sure our code adheres to it, and then we'll make sure our class (or classes) and their respective methods adhere to the single responsibility principle.

Furthermore, we'll make sure that it continues to function well within the context of the plugin, it's properly documented, and that it follows the WordPress Coding Standards.

In the meantime, if you're interested in reading more about object-oriented programming in the context of WordPress, you can find all of my previous tutorials on my profile page. Feel free to follow me on my blog or follow me on Twitter where I frequently talk about both.

As always, if you're looking for other utilities to help you build out your growing set of tools for WordPress or for example code to study and become more well versed in WordPress, don't forget to see what we have available in Envato Market.

With that said, the next tutorial in the series is going to be far more practical. That is, we'll be writing code, refactoring existing code, and applying everything we've learned in this tutorial. Until then, don't hesitate to leave any feedback in the comments.