This is just a quick post to announce that I’ve been accepted to speak at a pair of upcoming conferences.
First, I’ll be giving a new talk, Lose Your Head! Re-imagining WordPress’s Role in Content Presentation at WordCamp Minneapolis-St. Paul. The conference is being held on August 22-24 at the McNamara Alumni Center on the University of Minnesota Campus, and my session is scheduled for first thing Saturday morning.
In September, I’m flying to California to take part in WordCamp Sacramento, where I’ll be doing a reprise of my presentation, Modernizing Your Development Workflow Using Composer. The schedule hasn’t yet been released, but the conference will be held on September 21-22 at The Falls Event Center in Roseville, CA.
Unfortunately, neither of my submissions were accepted at WordCamp US this year, but I’m looking forward to visiting St. Louis in November, catching up with some old friends, and hopefully making some new ones. If you’re planning on going, give me a shout so we can find some time to get together!
I’ve been casually working on my Board Game Collector plugin off and on for awhile. It’s a fairly basic plugin that registers a custom settings page, post type, and WP-CLI command that allows you to connect to the BoardGameGeek API to pull in data for a given user’s board game collection. I’m still undecided as to the long-term utility of the plugin, so when I work on it, it becomes a playground of sorts for me to try out ideas.
A couple of months ago, I completely refactored the plugin to take advantage of the OOPS-WP library I had written for WebDevStudios, because I wanted it to more closely follow the style I’d established over the years for WordPress projects. This morning, after revisiting it once more, I decided I didn’t fully like the structure of the plugin bootstrap file, so I made a few minor tweaks. I’ve never actually written my approach down anywhere, so I figured a rainy day like today was as good as any to talk about my coding philosophy when it comes to plugin bootstrap files and class file organization.
Anatomy of a Plugin Bootstrap File
First, let’s take a look at the plugin bootstrap file for the Board Game Collector plugin is it exists in the develop branch of the repository this morning:
The main thing to notice here is that I’ve established that the sole responsibility of the bootstrap file is to determine whether WordPress can locate the files it needs to run. Any further plugin behavior is delegated to the main plugin file where services are instantiated, hooks are registered, constants are defined, and so on. Since I’m using Composer for class autoloading, I do want WordPress to check whether that autoloader exists locally within the plugin in case I installed it directly instead of requiring it via composer install somewhere from within the WordPress project.
One thing I changed this morning was moving toward the use of a try/catch block when attempting to initialize the plugin class. Previously, I was running a class_exists check to determine whether or not the plugin can run. But, in working with some enterprise WordPress multisite projects, I’ve come to learn that – depending on the particular configuration – class_exists might return true for a plugin that is deactivated on one site but active on another. In those projects, we had circumvented that behavior by passing in false as the second parameter to class_exists, but I think this try/catch approach is more explicit. If the class files are not loaded, then my plugin will catch the error and handle the notification/deactivation process.
And that, in a nutshell, is the entirety of the bootstrap process. Just about every plugin I write nowadays incorporates some version of this structure:
Check for the presence of a local autoloader
Try to instantiate the main plugin class on the plugins_loaded action and run it.
Display a notice and deactivate the plugin if anything went wrong.
Class File Organization
Next, let’s take a look at the file structure for this particular plugin.
By adhering to the PSR-4 standard for class autoloading, I’m able to organize the various classes that power my plugin into groupings relevant to their responsibilities. All class files at the root of the src/ directory have a namespace of JMichaelWard/BoardGameCollector, and from there, the namespace matches the relative path to the file. So, for instance, my CliService class, located at src/UI/Cli/, has a namespace of JMichaelWard/BoardGameCollector/UI/Cli.
The benefits of this approach are two-fold. First, when I need to make a change to a particular part of the plugin – say, updates to the API connections – I know exactly where I need to go, because everything is organized into top-level directories that describe what they are responsible for. Second, any classes referenced outside of that grouping can be easily located, because their namespace matches the file structure.
Today, many WordPress plugins still rely on a flat class structure which, sure, makes it easy to locate all of the class files, but I find that understanding the relationships between classes is far more challenging. This particular approach works for me, and perhaps it will work for you, too.
The Main Plugin File
Finally, let’s check out the main plugin file and see how things are structured.
There’s kind of a lot going on here, but in many ways, the main class file is a lot like the bootstrap file. Its job is to define a set of “services” – basically, processes for which the plugin is responsible for starting up – and make sure that those services are run. At this point in time, the Board Game Collector plugin has 5 primary services:
A ContentRegistrar, which is responsible for registering custom post types and taxonomies with WordPress.
An ApiService, which is responsible for registering custom API endpoints within WordPress and for communicating with the BoardGameGeek API.
A CliService, which is responsible for registering custom WP-CLI commands.
A CronService, which is responsible for setting up tasks that need to trigger at given intervals.
The Settings service, which is responsible for registering admin interfaces for working with the plugin inside of the WordPress dashboard.
Beyond that functionality, there are a few additional things I’d like to point out in this class file.
First, I’m using a Dependency Injection container called Auryn in this project. Auryn is, simply put, completely magical. On line 79 of the gist, the call to $this->injector->make passes in the current service class name to Auryn and leaves the instantiation of that object to it. If the class defines any other classes within its constructor, Auryn will load an existing instance of it if it finds one, otherwise, it will instantiate that dependency for you. The benefit is that your class constructors can be properly defined with the actual objects your class needs, making it easier to understand later what an object is made of. Auryn probably deserves a whole separate blog post of its own, so I’ll leave it at that for now.
Second, within the register_services method, I’m calling array_column on the resulting set of services and reassigning it to the $services property. This turns the indexed array into an associative array instead, and allows me – should I need it – to request a particular service object by its class name.
Lastly, after each of the service objects are instantiated, I pass the actual services to a register_service method, which passes in the main plugin file path to the objects that require it, and finally, calls their run methods to trigger the processes for those services. The benefit here is that register_service is type-hinted to the Service abstract class in OOPS-WP, meaning that if I add a service class name to the array inside of th main class, but forget to actually extend the abstract class, PHP will throw a fatal error. Errors are extremely helpful when attempting to abide by a given standard, and putting these guardrails in place for myself overtime have made me a better developer and made my own code a little more foolproof.
Hopefully this post gives you some ideas about approaches you can take to structure your own projects. I absolutely love working with object oriented code, and I’m hoping that as time goes on, we start to see more WordPress developers incorporating object-oriented practices into their plugins and themes. Clearly separating the responsibility of your code into sections, as I’ve demonstrated above, can make it easier for other engineers (or even your future self!) to understand what’s going on within your application, thereby reducing the time it takes to make fixes or to create brand new features.
If you happened to read this post and found it helpful or informative, please give me a shout on Twitter and let me know!
If you haven’t used Scorekeeper before, it’s a really basic score tabulation app – enter some people’s names and apply some numbers to the active player and adjust their scores. It’s handy for when you have an internet connection but no pen and paper and need to calculate player scores across a set of various criteria. On iOS, you can add the site to your home page as an app, and clicking on it will trigger a new instance of the app in your browser. I use it all the time, so it was very important to me that the look and feel of the app remained largely the same.
One new feature I added in this rewrite was the ability to reset the current state – basically, starting over and going back to selecting how many players there are. It’s a small detail, but it’s something that will enhance my own personal usage of the app.
Importantly, I spent the vast majority of my time completely logged out of my work Slack and e-mail, breaking down only yesterday afternoon to see what I’d missed in the week prior (hint: it wasn’t anything that couldn’t wait until tomorrow). I worked on a client-side app for my micro-blogging/Twitter alternative plugin, Into the Void, and reviewed Zac Gordon’s course about Headless WordPress on Udemy for inspiration and to level-up my own skills. But, for the most part, I didn’t spend much of this time in front of a text editor, and I think my vacation was better for it.
Tomorrow, I go back to work, and there’s still so much I didn’t get around to doing that I’m going to have to take care of in the coming weeks and months. I have talks to prepare and refine, new skills to learn, and personal projects to push along. The time off has been rejuvenating, though, and I feel better equipped to tackle these additional tasks after taking that time away than I did before.
Before this past week, it’d been five months since I’d last taken a scheduled PTO day. If you’re in a similar situation, I highly encourage you to give yourself a break, even if it just means taking a long weekend. Get out of town, enjoy the weather, read a book, or do whatever you enjoy doing that helps you unwind and takes your mind off your daily work tasks. You’ll come back refreshed and ready to tackle the challenges ahead.
Life moves fast; enjoy it. Work will be there for you when you get back.
The cat’s finally out of the bag: I’m going to Ohio in June! My presentation, Modernizing Your Development Workflow Using Composer, has been accepted by the fine folks at WordCamp Kent. I’m looking forward to sharing my love for the best command line tool in PHP with the WordPress community, hanging out with old friends, and getting to make some new ones. The event is happening at the Kent State University Hotel & Conference Center on June 15th and 16th, and I have the honor of following my friend Steve Grunwell‘s talk about PHP namespaces, something I’m especially glad to see being discussed in the WordPress community now that the minimum requirements have finally been bumped to PHP 5.6.
I mentioned it briefly in my last update, but I’ve also submitted a pair of presentations to WordCamp US (the same Composer talk, and another about object-oriented programming concepts), as well as one to WordCamp Minneapolis-St. Paul about building custom apps with WordPress as a back-end. I’m still awaiting word on those (as well as WordCamp Sacramento), but if everything gets accepted, I’ll be spending quite a bit of time behind the podium this year!
The One About Feel-good News
OOPS-WP got a mention on the latest Post Status newsletter! We’ve been having a lot of discussions about the open issues on the repo at work, and two of my wonderful WDS colleagues dedicated some of their 5 for the Future time this month working on contributions for those tickets. My hope is that this library can help WordPress developers better understand object-oriented programming concepts like SOLID, namespacing, and package use, while also giving them experience on working with third-party libraries. It feels great to see something I created as a way to make my own work a little easier gain a little traction within the community, and I’m grateful to Post Status for sharing the excitement about it.