Debugging your code in WordPress: Tools of the Trade

As this is going live I am currently giving a talk at @WPNYC the WordPress New York Meetup group.

There are two slides I skimmed over due to lack of time, but they are  an essential part of the talk. In order to fulfill my promise to provide the complete story I am publishing this post with the full story.

Warning, this blogpost is a bit of a braindump. It is intended as notes to use to explore further. If you need something clarified, don’t heistate to comment.

The first slide is titled:

Tools of the Trade

With the following content:

  • Separate development environment
  • console.log() / error_log() / var_dump($var); die();
  • debug_backtrace() / Xdebug
  • Inspect Element / Developer Tools
  • A good IDE
  • Simulators
  • Unit Testing

Let’s dig in…

Separate Development Environment

Never go commando, period. There are always exceptions to the rule — when you cannot reproduce a bug on your development server while it’s glaring at you from production — but you should avoid coding live on production at all costs. Sooner or later you’ll break something and your site will be down, and it was perfectly preventable.

This is as important as not ever modifying core WordPress files.

There are many ways you can implement a development server. Keep in mind that the closer your development environment is to production in how it functions, the fewer bugs you’ll have due to discrepancies in implementation of your code.

  • XAMPP, MAMP and WAMP are all easy to use out of the box server solutions. I started out with them myself.
  • Vagrant is a great way you can channel your inner sysadmin. But you don’t need to be one to use Vagrant. The good people at 10up support VVV. Or you can use the vagrant box one I built and use.
  • Get another account on the server you are hosting your live site on. It’ll be worth the money, just make sure it’s not accesssible from the “outside.” Member’s only plugins can help with that. Or use the htaccess or nginx.conf files to limit access by ip address.

console.log() / error_log() / <pre>var_dump($var); die();

THE key to effective debugging is to know what you’re dealing with. These tools help you peek under the hood, test your assumptions, and understand what’s happening.

  • Console is a VERY effective tool; its most used method is .log but it has a lot more. It’ll help you see what’s going on in your JavaScript code. We’ve come far from using alert().
  • error_log is similar to console, but server-side. Find out where your error logs are written to on your host. A server isn’t worth it’s salt if it doesn’t provide that. If you enjoy console.log check out console_log().
  • While the error_log is cleaner, it limits its output. I find I like to see things in the browser, sometimes. I use this pattern, a lot, when debugging. echo '<pre>'; var_dump($var); die();
    It will “dump” the variable in a preformatted html tag, then die().

debug_backtrace() / Xdebug

Xdebug provides a whole suite of extended debugging methods. You don’t need to start here, but if you’re looking to up your game, here’s where to go.

Inspect Element / Developer Tools

Volumes of ink has been used talking about devtools, so I won’t go in depth here. devtools-window.png

Firebug changed our lives. Read up on it, use it. Personally, I enjoy designing in it too. It’s not just for debugging.

I used devtoops to build this mockup to nag @Dropbox to request a feature.

A good IDE

I use PHPStorm. A lot of people swear by Sublime. One thing I like about PHPStorm is that it has deep integration with WordPress.

The reason why this is essential is that it does a lot in the background to ensure good code.

  • It can autoformat, which means you’ll reduce your syntactical bugs.
  • Deep link to method sources, so you can more easily see what’s happening under the hood.
  • Code completion will help you make sure you’re using the right method, and give you a reason to should “DAMN YOU AUTOCORRECT” every so often.

Simulators

If you’re expected to support a specific device, you better test in it. Unfortunatly we can’t all afford every device under the sun, but there are a lot of tools out there to help us with that.

  • Modern.ie provides virtual machines for testing different versions of Internet Exploreer.
  • Use a mobile emulator sometimes making your screen narrower won’t cut it.

Unit Testing

This is the single most important thing you can do to prevent bugs. It’s hard to get started. It’s overwhelming. But as the proverb says: the best time to plant a tree is 20 years ago, the second best time is now.

Protip: Think about testing BEFORE you write your code… Look up TDD.


The second slide is titled:

WordPress Specific Debugging Tools

With the following content:

  • define(‘WP_DEBUG’, true);
  • Debug Bar plugin
  • All the Debug bar addons!!!
  • Style Guides

define(‘WP_DEBUG’, true);

There are a number of constants you can define in your wp-config.php file that can help your debugging in WordPress.

Debug Bar plugin

The Debug Bar is the equivalent to the devtools, but for WordPress. If you enable it you’ll get a window into how WordPress runs that you can’t get easily otherwise.

All the Debug Bar addons!!!

Expanding on the previous tool. There are a ton of plugins that hook into the Debug Bar and extend it.

Style Guides

This isn’t necessarily a WordPress specific tip, but if you’re using PHPStorm it comes with an auto formatting preset of WordPress’ code style.

In any case, it doesn’t matter how you style your code (tabs vs. spaces) but only that you are consistent. If you are consistent with your coding style you’ll prevent a whole lot of bugs. You’ll prevent a whole lot more if you’re working with other people and you make sure you’re all styling your code the same way.

Our brains evolved to see patterns, if your code styling isn’t consistent, you’ll miss details. You’ll have bugs.

Conclusion

I hope this was helpful. There’s a lot I didn’t cover so as to not overwhelm. What’s really most important, which I covered in my talk is the following:

Make it work, then make it work well.

If you do this, your code will always be improving.

How to see if a class was added to an element using JavaScript

If you need to see if a class has been added to an element the easiest way is to trigger a new event when you add the class.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged');

The problem with this solution is what happens if you do not have control over the function where this happens. Like if it happens in the WordPress core, and you know that you should never ever change code in the core.

I needed this for a plugin I was buidling. I know that when I click on something an ajax call is fired, and I want to do something when the response comes back. The ajax call is encapsulated so I can’t hook into it, but when the response comes back it adds a class to an element.

This is what I did:

checkForAddedClass = function (observedElement, className, callback) {
    var count = 0;
    const observer = setInterval(function () {
        count++;
        if (500 < count || $(observedElement).hasClass(className)) {
            clearInterval(observer);
            callback();
        }
    }, 10);
};

When I click on that something, I call this function. It sets an interval that watches the observedElement selector to see if the className was added. If it gets added, or 5 seconds goes by, it runs the callback.

This is how it would be implemented:

checkForAddedClass('.attachment-details', 'save-ready', getUpdatedSettings);

Hope this helps if you’re dealing with a similar issue.

The Launch: A React+Redux WordPress theme

I think it’s just about done, so I decided to go ‘live’ with it.

You’re looking at it now. What do you think?

Here’s my first post about this theme…

I’ll probably tweak it over the next weeks, months. But I’m itching to give it a test drive. For now it’s good enough for government work… which means a lot less than it did just a few months ago.

I’lll also write more about the process, and how it works asap.

Find a bug? Let me know.

 

A Weekly Book Project

I’ve taken a step back from following all the podcasts I’d been listening to, for obvious reasons. I have the 3 I listen to, to keep up with the news… And that’s it. At a certain point, reading more news stories will only make me less effective.

In 2015 I set out to read a book a week, and ended up reading 83 books. In order to keep my sanity, I plan to attempt this project again this year.

I’ve already started, and you can follow my progress.

One thing I’d like to do differently this time around, as you might have noticed, is I want to absorb more of what I read. So I started writing a few paragraphs about each book, a takeaway, once I’m done.

I also wouldn’t mind company on this journey. I love discussing ideas, and what I’ve read and am thinking about. You can see from my 2015 list and my most recent additions that it’s an eclectic collection. So if you’d like to suggest a book you’d like to discuss, or know what I’m reading before I’ve finished, let me know and I’d be more than happy to discuss.

For the curious, the secret to accomplishing this, is to plan. I always have several books in my queue that I’m in the middle of, and a few shorter books (Shakespeare plays, etc.) that I can finish in a day or so in case the end of the week surprises me. That way I’m always ready to finish a book each week.

Plugin Concept: Request Post Feedback (with revisions)

I was listening to the Post Status Draft podcast from about a year ago where Brian, the founder of Post Status, interviews Matt Mullenweg.

In their discussion they Brian mentioned the Drafts with Friends plugin and how he’d like to see something like Google Docs collaboration, editing.

That got me thinking about what the MVP, minimum viable product, for that would look like… and I came up with the Request Post Feedback plugin.

Here’s how it works:

Under the content editor there is a new meta box. At the top of the box you can enter an email to generate a new feedback link. This is how Posts With Friends already works.

At the bottom of the meta box you can manage the different links that you already generated and see if someone has already given feedback.

When you send a link to someone they aren’t taken to the admin; rather, they are taken to the front-end of your site. Where the post would normally be, there is an embedded editor with the content of your post ready for their perusal.

When they submit their feedback it is saved as a revision post_type of your post.

What that means is that you can leverage the revisions browser comparison tool already built into WordPress and see what they suggested.

If you like the concept try it out. It’s not yet live on the WordPress plugin repository, because I haven’t decided if I’ll maintain it yet. But I welcome you to download it from the project repo and try it out. Please note: while I made sure that it was solidly built, it’s still an MVP/Proof of concept.

As always please share your comments below.

 

Developing A Theme for WordPress Using ReactJS, Redux, and the WP REST API

To being, check out the project here.

This is a work in progress, but I got enough done this weekend that I’d like to share.

I wanted to work on a project using ReactJS and Redux. I’ve heard a lot about it, and wanted to explore it on my own. I do that with every technology before I bring it to the office. Since WordPress incorporated the WP REST API in the core for version 4.7 I though that that might be a great opportunity to explore both the API using ReactJS+Redux.

There were a number of interesting challenges I faced building this. The idea was to make a theme that would work 100% like any other WordPress theme; that could be installed and work normally.

As it currently stands there are some missing features, which I’ll get to later. But this is past a proof-of-concept and well along the path to be fully operational.

I will explain more about how it all fits together in a future post, maybe when I load it onto this site. In this post I just wanted to muse about the process so far, and invite others to join in the project or share their ideas and implementations.

Endpoints: Handling Pretty Permalinks

The first challenge was to figure out how to handle “Pretty Permalinks.” You know what they are. Back in the early days of CMSs all URLs ran off of GET variables (http://blog.example.com?p=23). But because Google gave better SEO juice to readable URLs we all started getting urls that were readable. This was incorporated into WordPress as well.

The problem with implementing this in a single-page JS app is that the default path for posts is  /year/month/name-of-post/. That can make routing complicated. Not only that, but you can change the permalink format too. So in order for this theme to work, I’d have to handle that.

My solution was to have a catchall route and build a custom endpoint for Pretty Permalinks that would be powered by the url_to_postid() method. This ended up working pretty well and is what powers both single pages and posts.

Endpoints: Menus

Another challenge was how to handle menus. They’re dynamic, and not included in the current API. To solve this I borrowed the main class from the WP API Menus plugin. (I love GPL, don’t you?) It was written by Fulvio Notarstefano, and was beautifully implemented.

I contemplated having the menu data loaded as js variables on page load, since they don’t change. But I wanted the challenge of figuring out how to implement multiple versions of the same element with ReactJS+Redux, so they got their own endpoint.

Endpoints: Featured Images

I also modified the main post endpoint to include featured images so that I wouldn’t have to do a separate call for each image on archive pages.

Search

Another challenge, in general, was handling the different routes for different actions. It’s not all that complicated once you get the hang of it. But working in single page apps can get interesting, and if you’re not careful you can lose the benefits of using frameworks like Redux.

All in all the WP REST API is quite robust and is now polished. If you check out my redux actions you can see that I’m using the same endpoint for the main index archive, single posts and search. Which is really nice. I’ll be expanding this file for the taxonomies as well. Apparently all you need is to add a filter GET variable.

What’s still missing from the project?

There’s still a lot to do. First and foremost, there is currently only minimal styling.

There are a whole lot of things that are needed to make it a theme the might be accepted into the theme repo. First of all, I haven’t done anything with taxonomies yet.

I’d also like to add widgets. That is another interesting problem which I’ll probably solve the same way I did pretty permalinks — add a new endpoint just for them. I’ll have to render them completely on the server, then pass them down via the API. It’s not pretty, but it should work.

I’ll also want to clean up the hooks that run before the page loads. Since the entire theme is running off the API, directly from the index.php, it won’t need a lot of the server-side processing, as that is done already in the API.

The customizer isn’t playing well with the menus, I’ll have to figure that out.

I’m sure there’s a whole bunch more that needs to be done too. I’ll write about what I discover in the summary post once (if) this theme goes live.

Closing thoughts

It’s a fun project and I’ll look forward to playing more with ReactJS and Redux. The first thing I noticed was how snappy it was. It also forces you to think about the different components in a very healthy way. When designing components, each one should be independent. You should be able to drop any one in any other project (for the most part) and use it with minimal wiring up. That’s good coding practices.

Join me!

If you find this project interesting please feel free to share with me your ideas for it.

Thoughts about “Who”

Finished reading “Who” this week. I found it an interesting approach to hiring. I’d read it if I were looking for a job as well to prepare for interviews, though it’s not designed for that.
Takeaways:

  • Take hiring seriously, this should be obvious but it’s easy to let it get lost in all the other work.
  • Manage the task of hiring as your would any other project with a clearly defined role, and process in advance.
  • Don’t hesitate to walk through every aspect of their career with them, ask about anything ambiguous. Everyone has things they sweep under the carpet, so it’s important to understand this when you are evaluating a candidate, but you also want to make sure you don’t miss things you need to know first.

Things I would change: 

  • I found the tone of the book somewhat annoying. It talks itself up a lot. It backs up it’s self-promotion, but there could have been a better way to do it.
  • This makes the process even more intimidating, something that’s already difficult to do.

Is npm not installing properly on Vagrant running on Windows?

Get a Mac! Kidding. (I actually think Microsoft has been more innovative lately.)

Run the flag --no-bin-links when you install anything with npm and it will fix your issue.

I have a dev Vagrant that I share with my team. I tend to mock things up when I’m playing around at home in the evenings. I work on a Mac at home. So when I confidently came into work with the plan to set up a box for my team to work on, I lost a bunch of time trying to figure out why the npm development tools I wanted, would not install.

According to the npm documentation:

The --no-bin-links argument will prevent npm from creating symlinks for any binaries the package might contain.

Why? I found this discussion on the Vagrant github:

…there is a fundamental problem with using Vagrant + VMWare Workstation + Windows + Linux VMs…

It seems that VMWare on Windows simply does not support the ability to create a Linux symlink in a shared folder.

 

Another option is to set bin-links to false in your global npm configurationnpm config set bin-links false 

This will mean that you won’t have to type in the flag --no-bin-links each time, which might be a good solution if you are trying to build development tools to make your team’s lives easier.

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:

wp-asssets-manger.php

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.

inc/Asset_Post_Type.php

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.

inc/Asset.php

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.

inc/Serve_Attachment.php

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.

inc/Check_Asset_Restrictions.php

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.

inc/Admin.php

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

inc/Update_Assets.php

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.

inc/Log_Assets_Access.php

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.

js/asset-manager.js

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 wp.media.
    Back when I first built this, wp.media didn’t exist. I implemented  Plupload as a jQuery plugin in my original version. By using wp.media here I’m making the plugin “future proof.” If ever WordPress moves away from Plupload, they would implement whatever alternative via wp.media.
  • 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.

Conclusion

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