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:
- Define a roadmap of where we're going.
- 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.
Our Roadmap
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:
- A local development environment that includes at least PHP 5.6.20, the Apache web server, and a MySQL database server. MAMP 4 is perfect for this.
- A directory out of which WordPress 4.6.1 is being hosted.
- A text editor or IDE of your choice that you're comfortable using for writing a plugin.
- A working knowledge of the WordPress Plugin API.
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:
- We define an interface much like we do a class, but we use the
interface
keyword. - The methods that are defined in an interface have to the public (as opposed to being
protected
orprivate
) 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:
<?php /** * Defines a common set of functions that any class responsible for loading * stylesheets, JavaScript, or other assets should implement. */ interface Assets_Interface { public function init(); public function enqueue(); }
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:
<?php class CSS_Loader implements Assets_Interface { /** * Registers the 'enqueue' function with the proper WordPress hook for * registering stylesheets. */ public function init() { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) ); } /** * Defines the functionality responsible for loading the file. */ public function enqueue() { wp_enqueue_style( 'tutsplus-namespace-demo', plugins_url( 'assets/css/admin.css', dirname( __FILE__ ) ), array(), filemtime( plugin_dir_path( dirname( __FILE__ ) ) . 'assets/css/admin.css' ) ); } }
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):
<?php /** * Dynamically loads the class attempting to be instantiated elsewhere in the * plugin. * * @package Tutsplus_Namespace_Demo\Inc */ spl_autoload_register( 'tutsplus_namespace_demo_autoload' ); /** * Dynamically loads the class attempting to be instantiated elsewhere in the * plugin by looking at the $class_name parameter being passed as an argument. * * The argument should be in the form: TutsPlus_Namespace_Demo\Namespace. The * function will then break the fully-qualified class name into its pieces and * will then build a file to the path based on the namespace. * * The namespaces in this plugin map to the paths in the directory structure. * * @param string $class_name The fully-qualified name of the class to load. */ function tutsplus_namespace_demo_autoload( $class_name ) { // If the specified $class_name does not include our namespace, duck out. if ( false === strpos( $class_name, 'Tutsplus_Namespace_Demo' ) ) { return; } // Split the class name into an array to read the namespace and class. $file_parts = explode( '\\', $class_name ); // Do a reverse loop through $file_parts to build the path to the file. $namespace = ''; for ( $i = count( $file_parts ) - 1; $i > 0; $i-- ) { // Read the current component of the file part. $current = strtolower( $file_parts[ $i ] ); $current = str_ireplace( '_', '-', $current ); // If we're at the first entry, then we're at the filename. if ( count( $file_parts ) - 1 === $i ) { /* If 'interface' is contained in the parts of the file name, then * define the $file_name differently so that it's properly loaded. * Otherwise, just set the $file_name equal to that of the class * filename structure. */ if ( strpos( strtolower( $file_parts[ count( $file_parts ) - 1 ] ), 'interface' ) ) { // Grab the name of the interface from its qualified name. $interface_name = explode( '_', $file_parts[ count( $file_parts ) - 1 ] ); $interface_name = $interface_name[0]; $file_name = "interface-$interface_name.php"; } else { $file_name = "class-$current.php"; } } else { $namespace = '/' . $current . $namespace; } } // Now build a path to the file using mapping to the file location. $filepath = trailingslashit( dirname( dirname( __FILE__ ) ) . $namespace ); $filepath .= $file_name; // If the file exists in the specified path, then include it. if ( file_exists( $filepath ) ) { include_once( $filepath ); } else { wp_die( esc_html( "The file attempting to be loaded at $filepath does not exist." ) ); } }
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.
Comments