Refactoring a WordPress plugin, Object-oriented, a start

I recently dissected  an Object Oriented WordPress plugin boilerplate. This exploration was part of a project I am undertaking to explore best practices for implementing Object Oriented principles in WordPress development.

When it comes to implementing coding principles, I’m generally not a purist — I aim to be utilitarian. One of the dictums I drum into my team is: “Make it work, then make it work well.” Do not take that to mean I’m sloppy, the second half of that statement holds as much weight as the first.

In the spirit of “make it work well”, I decided to refactor my Assets Manager plugin for this exploration, as I have not updated it in a while.

My goal here was not to create a pure Object Oriented plugin implementing all the glorious principles. There is a lot more I can do, and I will discuss some of those ideas as I explain what I did. Mainly, in this refactor, I wanted to accomplish the following:

  1. Implement the Single Responsibility Principle.
  2. Decouple the various components of the plugin from each other.
  3. Lay the groundwork for further implementation of more principles.

Single Responsibility Principle

Of of the banes of every developer is cutting through spaghetti code. I’ve discovered — from refactoring multitudes of lines of code — that the simplest, most effective way to reduce and prevent spaghetti is by applying this principle. Like spaghetti, your code cannot get tangled if it’s too short to tangle up.

Decouple the various components

While recompilation isn’t an issue with PHP/WordPress, there are still benefits to decoupling. First, reusability: if your components work independent of each other you can stash your pieces away for another project. You also don’t have to repeat your code if you need the same functionality elsewhere. Don’t Repeat Yourself!!!

But perhaps, more important than reusability is stability. The more interdependent components are in your project, the more fragile your project is overall. If you change one thing, the more other components depend on that piece, the more chance you have that you are breaking one of those other components.

This is the whole reason for the Open/Closed Principle as well as the Interface Segregation Principle. Aside from SOLID, though, this is also the reason why WordPress is riddled through and through with hooks. WordPress hooks allow for developers to change the functionality of the core, or other people’s plugins, without having to change the core, or foreign plugin, code.

Taking Stock

If you look at the previous version you’ll see that the extent of Object Oriented implementation is an encapsulation of the code, and that’s about it.

This isn’t a bad practice per-se. If you are going to keep to best practices of compatibility standards with WordPress, you cannot use php namespaces in your plugins. Namespaces were introduced in PHP 5.3 and, as of writing this, WordPress still supports as far back as PHP 5.2.4.

A first step you can take when implementing Objects in your WordPress plugins is to wrap your code in a class. If you do this, you do not have to worry about the names of your functions conflicting with the names of other functions in other plugins. This approach is called the “God Class,” as it creates one class that does it all. It’s not all that sophisticated, nor is it really Object Oriented either.

On this topic, once you start adding classes to your plugins, there is a fascinating and thorough breakdown of the different ways to instantiate a WordPress plugin as a class on the WordPress Stack Exchange community.

Following is a breakdown of the files in the new-and-improved plugin:


This should be renamed to match the directory (assets-manager), but I’m not sure whether the plugin upgrade process will work if I do this. Because this file is not named as the plugin directory, it makes generating test suites more complicated, but it’s also not a big deal.

The main job of this class is to instantiate all the other pieces of the plugin; I may implement an autoloader here at some point. While this class is dependent on ALL the other classes, since the only thing it does is instantiate all the other classes, it still is a fairly stable class. It doesn’t care about the intricacies of the other classes it uses. As long as the function names stay the same, you will only have to change this class if you need to add another component.

The other minor job of this class is to ensure that the rewrite rules are flushed when the post type is being created. Yes, this class is supposed to do one thing, but other, more pure ways of doing this would be convoluted — creating then deleting options in the database. I thought that that was silly to do simply to keep with a guideline, so I opted for this small infraction.


When classes do one thing, they tend to be boring, and that’s a good thing.

I have an empty constructor here because the logical alternative would be to put into it  the hooks call. That would make tests more complicated, so I didn’t do that.


I tried to include in here all the specific logic about how each individual asset works: the metadata, when are users allowed to access an asset, the asset link, etc. I did this to pull it away from the god class. The next step will be to pull out the specific restrictions as components onto themselves.

Currently, they all hook into pre_asset_serve which is a hook I put into the class that serves the asset. Each restriction should independently hook into the asset class.

Additionally, the UI is still intertwined with Admin.php, so if you were to add features to the asset, you would need to change that, as well as the JS file. I think this is a step in the right direction, perhaps next iteration will include this decoupling.


This does exactly what it says, nothing else. It hooks into WordPress before headers are sent, if the request is an Asset, it serves that request.

This was built with the Open closed principle in mind, open for extension, closed for modification. One of the most powerful features of WordPress are the hooks; which, are the embodiment of the Open closed principle.

Every WordPress developer learns at one point or another early in their career that you do not change the core, or anything that may be updated for that matter.

How is this learned?

Well, they make a change, to the core, or a plugin, or theme. Then, at some point in the future they forget that they had made that change and they update whatever it is they made the change to.

And everything breaks.

Well, maybe not everything; but whatever they were trying to accomplish with their modification is now lost.

Hooks are peppered throughout the core, well developed themes, and plugins. They allow other developers to hook into the code and tell it to do something without changing the code. This way when an update comes out, they can update without losing those changes.

Serve_Attachment.php has the hook do_action( 'pre_asset_serve', $this->attachment_id ); before the asset is served. I eat my own dog food here and hook into that action from Check_Asset_Restrictions.php to see if that asset should actually be served.


This is the other side of my implementation of the Open Closed principle, discussed in the previous file.

This class hooks into pre_asset_serve and runs all the checks it needs to. This class needs to have a certain amount of knowledge about how Asset.php works, so it’s not ideal. This is another example of how it’s a work in progress.

The fun thing about this is it runs entirely on hooks. It hooks into pre_asset_serve and it has a filter itself through which others can change the no_serve_message.


This class is responsible for the admin display of the assets on the post type page.

As I wrote above. Ideally, each feature of the asset — expires, require login etc. –should be a separate component hooking in here, and where the file is served. Perhaps I’ll do that in the next iteration. Doing that would coincide better with the Interface segregation principle.

As-is, it think this approach is better than it was before. The admin display


This is the biggest violation of the Single Responsibility principle. On the one hand it’s responsible for the AJAX requests. On the other hand it’s responsible for ALL the AJAX requests. It wouldn’t be difficult to break up. Next version.


Completely self-contained, hooks directly into pre_serve_asset, does (almost) one thing.

I put create_log_table() into here, because it is a single function that is needed to make it work. It’s static so it can be accessed on plugin activation without instantiating the whole class.


This could benefit from the implementation of a JavaScript framework. I’m considering BackboneJS for the next iteration of the plugin. I’d use that library since it’s already included in the WordPress core.

My goal for this file was twofold:

  • To implement
    Back when I first built this, didn’t exist. I implemented  Plupload as a jQuery plugin in my original version. By using here I’m making the plugin “future proof.” If ever WordPress moves away from Plupload, they would implement whatever alternative via
  • To break apart big functions.
    There was a huge spaghetti mess here before. Now that each “thing” is its own function I can iterate further in the next version.


This isn’t a finished product, nor is it the best I can do. But it’s a good step in the right direction. I learned a lot exploring what other people are doing with their plugins, and it was fun to flex my refactoring muscles to do this project. I hope you enjoyed, I did!

If you have any ideas about what steps you would want to see taken next, feel free to comment below, or use the contact form on the contact page.

Image credit

Technological Evolution, Microsoft vs Apple

I’m writing this from my iPad Pro with the Smart Keyboard. It’s a beautiful experience. It’s also a natural evolution of where technology has been going.

This past week Microsoft has displayed that it understands this. Apple has not.

Writing here is not a perfect experience: I still think multitasking on iOS could benefit by some improvements. But I enjoy being able to reach up, touch the screen and do things. When I switch back to my MacBook Pro, I’ll invariably find myself reaching up to the screen to manipulate something.

There have been several innovations along the path of technological evolution that have sparked exponential adoption and further innovation.

“Evolutionary processes creates a capability and uses that capability to bring on the next stage.”

– Ray Kurzweil, TED (Minute 5:21)

There is a rabbinical tradition that on the sixth day, before sundown, God created the first pair of tongs–giving the world’s first blacksmith the necessary tool with which to make more. But it’s more likely that man iterated on his tools, building up to some sort of tong. This is how technology develops.

Similarly, with interfaces, we build off previous iterations of interfaces towards more efficient tools. Punch cards led to keyboards; command line interfaces led to GUIs; mice led to touchscreen.

“Progress of technical science is characterized by the fact: first, that more and more energy is utilized for human purposes, and secondly, that the transformation of the raw energies into useful forms of energy is attended by ever-increasing efficiency.”

– William Ostwald, Efficiency

Our tools progress towards being more efficient. That is what defines technological progress. Whatever issues that are lacking in touch interface are not because of it being less ideal an interface than command line (no, VIM is not better)–it is because of the implementation of the tool. Newtons were horrific, but iPhones are a beautiful experience.

Another concept Kurzweil talks about is exponential growth. Not only did RNA lead to the Cambrian period, it led to the Cambrian explosion. Not only that, but as far as we know, all cellular life has DNA, an evolutionary step past RNA. When a biological process is surpassed, it tends to be left behind. This is also true of technology. Our trains are not steam-powered anymore, nor do we use vacuum tubes in our computers.

iOS was originally forked off of OSX. It was done so because OSX was a solid platform, but somewhat over-bloated for the limited resources of the original iPhones. There were speculations about if/when they would be re-merged.

Microsoft has already done so with Windows. While I’m not a big Windows fan, I will admit that that was the right play and the proof of that is this past week’s tech announcements from both companies.

I’ve been an Apple fanboy for a very long time, it pains me to say this.

It is doubtful whether a contextual touchscreen on a keyboard provides added efficiency in your workflow–if it does, it is linear. This past year Apple has not demonstrated exponential growth, their iterations have been little more than linear, or catching up to parallel technologies. Waterproofing a watch, putting an accelerometer into a TV remote, adding zoom to a camera. These all add to the experience, but other tech is surpassing these technologies.

Microsoft, on the other hand, has been developing entirely new interfaces. Kinect tracks your movement, creating a whole new way to interact with games. Hololense will bring AR to a place where it can be useful.

The Surface Studio looks beautiful. They are embracing touch interface as the next step in the evolution of interfaces. It’s more than a linear step along the way–I don’t know if it’s exponential, but it shames a slightly augmented keyboard. It combines the power of a desktop with the interactive interface of a tablet. The result looks like a better experience than the sum of its parts. This is technological progress.

Cover image 

How to Globally Ignore files from git


  1. nano ~/.gitignore
  2. git config --global core.excludesfile '~/.gitignore'


Git is all the rage, why wouldn’t it be? You can save every iteration of your work; it’s the persistent undo button for developers. Seriously, if you’re not using it, start now. Find a tutorial, stop everything you’re doing and get on that. It will make your work 1000% more efficient.</intro>

One issue I came across with my workflow is that my Mac, like everyone else’s, places a .DS_Store file in every directory. There is absolutely no situation in which I could possibly my .DS_Store files to be included in my repo.

The Solution?

Global .gitignore files.

If you’re new to git, a .gitignore file (don’t forget that preceding period) is placed in your git repo. When you are committing git will ignore all the files in that directory, and deeper, that are listed in the .gitignore file.

If you’ve never used it before, here’s how .gitignore works. Typically you would add directories that hold dependencies that can easily be fetched again and take up space.

You can also set a global .gitignore for the files you know  you will never want to include in any repo (like the .DS_Store files).

The first line in the TLDR above creates the file that will be used as the global .gitignore in a good location for such a file. Typically config files for a specific user are placed in that user’s home directory. ~/ is a shortcut to that location.

The second line sets the .gitignore file you just created to be used in the global config. This way you never have to add the file specified there to any local .gitignore files in the future.


Just like with all global config settings, make sure you only put there things you’ll never want to include in any project whatsoever. Down the line you might wish you handn’t set a config file when you’re pulling your hair out trying to figure out why file X or Y isn’t getting included in your project.

Source, image

E7 – We hold these truths to be self-evident

On August 28, 1963 Dr. Martin Luther King Jr. gave one of the most powerful speeches of all time.

I know I cannot do this speech justice. But to be honest, I’m not doing any of these speeches justice.

I’m studying and I’m practicing.

I’m studying history, and what makes a great speech and I’m practicing my oratory. I’m doing so with the words of masters in my mouth, and I’m grateful for the opportunity to study these great words.

So please forgive me for butchering some of the most moving and eloquent words spoken…

Why this speech?

First and foremost because, as Dr. King stated, my destiny is tied up with their destiny and my freedom is inextricably bound to their freedom.

I hope that one day it will seem confounding that this speech needed to be said, because it’s message is obvious and should be obvious to everyone.

But sadly today, this speech still rings true today, and it needs to be read and reread, and listened to not for it’s stunning poetry, but for it’s message.

Coding Katas: Insertion Sort

Writing tests for sorting algorithms are interesting. The main issue is that the tests would be the same regardless of which algorithm you chose:

  1. Given [1], sort returns [1]
  2. Given [1,2], sort returns [1,2]
  3. Given [2,1], sort returns [1,2]
  4. Given [1,2,3], sort returns [1,2,3]
  5. Given [2,1,3], sort returns [1,2,3]

In Test Driven Development, when writing code for a test, you are supposed to write the least amount of code necessary to make the current test pass. So if you are going to write algorithms for sorts. All sorting would be the same process:

To resolve the first and second tests all you need to return is the array given.

To resolve the third test, you can check if the first element in the array is bigger than the second, if it is, reverse the array, and return that, otherwise, return the array.

To answer the fifth test, you write the whole damned sorting solution. Whether you’re solving insertion sort, binary sort or quick sort — it doesn’t matter.

Since I wanted to write tests for sorting algorithms I decided that the best way is to think about the solution and incorporate that into my tests.

Insertion sort does what you would typically do if you have a hand of cards. You go from the beginning, each consecutive card that is out of order, you take out of your hand and place in the right spot.


So I built my tests for insertion sort to solve finding the correct spot for a new value in an array first, then implementing the sort was trivial.

Writing this in JavaScript meant that the insertion did not require moving each element over one in the array as it would in a language like Java. Once you have the position, you can remove the element from the array and put it back right where it goes.

Here are the tests I built. You can use my tests for insertion sort, or peruse my solution for insertion sort

  1. Can create InsertionSort object
  2. When 1 is given to [], getPositionForNewVal returns 0
  3. When 3 is given to [2,7,4], getPositionForNewVal returns 1
  4. When 9 is given to [2,4,7], getPositionForNewVal returns 3
  5. Insert 2 at index 0 into [2,4,6,3,5], should return [2,2,4,6,3,5]
  6. Insert 2 at last index into [2,4,6,3,5], should return [2,4,6,3,5,2]
  7. Insert 2 at index 2 into [2,4,6,3,5], should return [2,4,2,6,3,5]
  8. Slice index 0 from [2,4,6,3,5], should return [4,6,3,5]
  9. Slice index 2 from [2,4,6,3,5], should return [2,4,3,5]
  10. Slice index 5 from [2,4,6,3,5], should return [2,4,6,3,5]
  11. When [3,2,5,4,7,4] is given, sort returns [2,3,4,4,5,7]
  12. When [8682,2602,5961,4659,432,8230,111,3921,2841,5913,4876,800,6748,5720,4660,327,2305,3571,9919,8277,6168,2305,3359,9292,7043] is given, sort returns [111,327,432,800,2305,2305,2602,2841,3359,3571,3921,4659,4660,4876,5720,5913,5961,6168,6748,7043,8230,8277,8682,9292,9919]

Code Katas: Linked Lists

I explored in a previous post the idea of a coding kata. I explained that I thought that data structures, design patterns, and fundamental algorithms are ideal for such practice.

I think a good way to practice them is to start with the tests, and practice the kata from there. In this light, last week I put forward the tests for the Stack kata.

This week it’s Linked Lists.


A linked list is a data structure is a linear collection of data elements, called nodes. In it’s most basic form each node contains two pieces of information:

  • The data itself
  • A pointer that points to the next node

I came up with 20 tests (22 assertions) to implement this:

  1. New linked list init
  2. New linked list, next is null
  3. New Linked list, getLength is 0
  4. Add value once to list, getLength is 1
  5. Add value once, searchValueAt(0) returns value
  6. Add value once, searchValueAt(1) returns null
  7. Add two values, getLength is 2
  8. Add two values, searchValueAt(1) returns second value
  9. Add two values, searchValueAt(0) returns first value
  10. Remove node on empty list, length is 0
  11. Add value, remove node, length is 0
  12. Add value, remove node, list is empty
  13. Add value, remove node, add value, first is second value
  14. Add two values, remove second, length is 1
  15. Add two values, remove at third position, length is 2
  16. Add two values, remove second, first is value and next is empty
  17. Add two values, remove first, length is 1
  18. Add two values, remove first, first is second value
  19. Add three values, remove second, length is 2
  20. Add three values, remove second, first is value and second is third value

Here’s my implementation, but really I’m more interested in yours. Post a link to your repo below!

Image credit

Code Katas: The Stack

I explored in my previous post the idea of a coding kata. I expressed that I did not think just any exercise was worthy of being called a kata, because not all exercises are worth of practicing more than a few times. But there are concepts in computer science that are worth repeating again and again, to become a better programmer.

What brought this first to my attention was Uncle Bob’s screencast on the Stack kata where he demonstrated Test Driven Development implementing the Stack data structure.

As a kata, it’s beautiful. It’s a fundamental concept that could be implemented in many different ways. Also, interestingly, it would be implemented differently in different languages. So there is a lot to explore here.

Before putting forward the tests Martin used, I’ll recap what a Stack is.

A stack works like a stack of plates.

  • The first items into the stack are the last items to be taken off.
  • If you have a limit to how many plates will fit on your shelf, you can’t fill it too high.
  • You can’t remove from a stack if it’s empty.

That’s basically it.

Here are the tests that Uncle Bob lays out in his screencast.

  1. Can create Stack object.
  2. Newly created stacks should be empty.
  3. After one push, stack size should be one.
  4. After one push and one pop, should be empty.
  5. When pushed passed limit, stack overflows.
  6. When popped passed limit, stack underflows.
  7. When two values are pushed then one is popped, size is one.
  8. When one is pushed one is popped.
  9. When one and two are pushed two and one are popped.
  10. When creating stack with negative size, should through IllegalCapacity.
  11. When creating stack with zero capacity, any push should overflow.
  12. When one is pushed, one is on top.
  13. When stack is empty, top throws empty.
  14. With zero capacity stack, top throws empty.
  15. Given stack with one two pushed, find one and two.
  16. Given a stack with no two, find two returns null.

In my implementation and the tests I used, I ignored everything relating to capacity (5,10,11,14) because I implemented my stack in JavaScript. I could implement overflows, but JavaScript does not require a capacity when instantiating an array.

Want to give it a shot yourself? Post your implementation in the comments.