DIY WordPress: Debugging Plugins Using FirePHP

(Reading time: 7 – 12 minutes)

You know you want to program WordPress plugins… but where to start? There’s so much to learn!

Turns out, programming WordPress plugins isn’t that hard, if you know how to use the right tools for the job. It’s no different than any other activity.

For example, you can cut just about anything with an axe: an oak tree, a loaf of bread, your leg (don’t ask ☹), whatever’s in the way. But a knife works much better.

Likewise, really sharpening your code requires exactly the right tool for the job, and a good debugger is essential.

To me, debugging so essential that I sneered at PHP and Ajax applications for years. Debugging code by printing variables and pressing CTRL-F5 is inefficient. There just weren’t very many easily available tools for PHP debugging, outside of installing (and learning) an entire application system such a Zend. That’s too much trouble!

FirePHP changes the landscape: debugging PHP just got radically easier.

Let’s do some WordPress PHP debugging

Website In A Weekend reader Michael W emails:

How do you debug PHP (e.g. for developing a new wordpress plug-in)? Do you use XDebug, FirePHP, or something else? A post about setting up and using one, or both, of these would be helpful.

I have succeeded in using XDebug and a windows-based debugging client (for debugging Ajax/REST requests between a jQuery front-end and a PHP back-end). I have installed, but not successfully used, FirePHP yet (haven’t worked on the server-side part).

Very timely question!

Debugging WordPress and plugins can be a real pain. Having tools for debugging is tremendously helpful. Practically necessary. I took a look at both XDebug and FirePHP. Of the two, FirePHP was a little more tractable, so I installed it on localhost. Here’s my experience.

Installing FirePHP debugging application

I chose to use a standalone version of FirePHP, installing using PHP’s pear facility on my Ubuntu Linux distribution running in VMWare:

doolin@doolin-ubuntu:~$ sudo pear channel-discover pear.firephp.org
Adding Channel "pear.firephp.org" succeeded
Discovery of channel "pear.firephp.org" succeeded
doolin@doolin-ubuntu:~$ sudo pear install firephp/FirePHPCore
downloading FirePHPCore-0.3.1.tgz ...
Starting to download FirePHPCore-0.3.1.tgz (22,630 bytes)
........done: 22,630 bytes
install ok: channel://pear.firephp.org/FirePHPCore-0.3.1

As it turns out, I was also able to install FirePHP using cygwin on Microsoft’s Window’s Vista as well. The key to installing on Vista was that my PHP installation is installed in Windows, not in cygwin, so I had to use “pear.bat” command. The pear commands would probably work as is with a cmd prompt in Windows.

Moving right along, I followed the instructions exactly and was able to run the FirePHP demonstration.

First test on hRecipe Plugin

Anytime I write a new plugin, I like to be reassured that the control of flow is proceeding normally. That is, how I want it to proceed. Specifically, I want to ensure that WordPress is reading and and activating the plugin correctly. FirePHP makes it easy to check: write to the console log when the plugin is loaded and when it’s activated.

First, we need to tell WordPress to load the FirePHP code, in this case using the object API. Here’s the code in hrecipe.php to make that happen:

43
44
require_once('FirePHPCore/FirePHP.class.php');
ob_start();

Next, let’s log the initialization function which is read every time WordPress makes a sweep through the plugin directory:

55
56
57
58
59
60
61
62
if ( isset ($recipe)) {
 
    $firephp = FirePHP::getInstance(true); 
    $dt = date("l dS \of F Y h:i:s A");
    $firephp->log($dt,'date/time');
    $var = array('i'=>13, 'j'=>27);
    $firephp->log($var, 'if (isset())');
    register_activation_hook( __FILE__ , array ($recipe, 'hrecipe_activate'));

Line 55 ensures that all the necessary files were read correctly. If not, the plugin exits. Our next call will be triggered as a result of executing line 62. And here’s hrecipe_activate(), with the last logging call:

7
8
9
10
11
    function hrecipe_activate() {
 
       $firephp = FirePHP::getInstance(true); 
       $var = array('i'=>11, 'j'=>22);
       $firephp->log($var, 'Activate');

Let’s see what this looks like with FirePHP implemented in the WordPress hRecipe plugin. Firing up Firefox and enabling the Firebug/FirePHP addon results in the following console view:

FirePHP output from activating hRecipe plugin

FirePHP output from activating hRecipe plugin

The if (isset()) label (blue arrows) is emitted when the hRecipe plugin is read. The red box is the log message from the recipe class activation function. Activation functions require getting the path to the class file correct, which can be a bit tricky if the plugin name doesn’t match the file or directory names. The array values (13, 27) are meaningless; they have been kept as place holders for the next round of debugging.

Here’s something interesting which I did not know about WordPress: there is a function somewhere in the chain that refreshes the plugin directory once every minute. Here’s a screenshot showing what that looks like:

FirePHP showing 1 minute refresh

FirePHP showing 1 minute refresh

The red box shows the series of refreshes, in this case 13 seconds after each minute, shown in the orange boxes.

I’m assuming that this is normal behavior, because I am running this installation of WordPress on localhost. This is a pretty good assumption.

If I had discovered this behavior running from an external host, I would have seriously considered whether this was normal behavior or not. What if it wasn’t? Could mean I’d been hacked, but that’s a digression best left for the future.

These kinds of serendipitous discoveries are normal once you dig deeper using the right tools. I could have seen this using the Fiddler network debugging tool, had I known what to look for. With FirePHP, it showed me while I was looking for something else. Very convenient.

How FirePHP works

The short story:


FirePHP logs your debug messages to the Firebug console.

FirePHP consists of a server side library that allows you to examine any PHP variable without breaking the application’s response. That is, the application still works “the same” as it would without FirePHP by breaking the HTTP responses into parts.* Some parts of the HTTP response carry the usual application data (your PHP-generated webpage), other parts carry the FirePHP debugging data. You access this data using the FirePHP extension for Firefox (runs in the Firebug application).**

Last, but not least, FirePHP is distributed under a BSD license. If you don’t know what that means, it’s a good thing.

Read more about FirePHP

The official FirePHP website is probably the first place to visit for getting started. All the information you need for installing and using the addon is there.

Christoph Dorn presents Integrating FirePHP for Ajax Development, an excellent guide for getting started with FirePHP and one of the primary references for this article. In his own words,

My purpose in this column is to introduce you to FirePHP, the problem it solves, and how it is intended to work within your application for maximum benefit. I will present some useful high-level knowledge to make it easier for you to integrate FirePHP into your application.

Dorn continues, covering a few basic methods for debugging PHP, noting that learning some Javascript along the way is probably a good idea, and explaining the FirePHP architecture.

Six Revisions weighs in with How to Debug PHP Using Firefox with FirePHP, another excellent article for getting started. Here’s what the author Nuno Franco da Costa has to say:

FirePHP is an add-on for an add-on: it extends the popular in-browser web development tool called Firebug with an API for PHP web application developers. FirePHP is free and easily attainable via the Mozilla Add-Ons section on the official Mozilla site.

da Costa goes further into logging than we did here, and covers Information, Warning and Error log messages.

Turing Tarpit offers a WordPress logging plugin based on FirePHP code: WordPress Logger: A plugin that displays log messages to the Safari and Firefox console from PHP. Chandima Cumaranatunge provides this great list of WordPress logging features:

  • Log debug messages directly from themes and plugins.
  • Display log messages in the browser console, without muddying up the browser display.
  • Displays complex structures such as arrays and objects in pretty print.
  • Shows the line number and file from where the message was logged (you won’t lose track of log statements).

I’ll be checking out this WordPress logging plugin myself. If you have already used it, let us know how you liked it!


* Actually, debugging always changes application behavior in some way, but for our article, FirePHP gets it close enough. If you wanna go down that rabbit hole with me, buckle up, because it’s going to be rough ride.

** That’s a lot of fires to keep track of. It’s easy to keep track of once you have everything installed and operating correctly.

† Checking for a hack: Look at localhost behavior, known clean; search the wp-hackers list for cron and scheduling; read through the WordPress plugin source code for more clues to normal behavior.

How To Build Your WordPress Plugin Development Infrastructure

(Reading time: 8 – 13 minutes)

So you wanna write a plugin?

Cool.

Writing a plugin is like accomplishing any other task:


The key to any endeavor is proper prior planning.

And understanding what you want to achieve.

If your goal is to adjust an existing plugin with some minor tweaks, you can pretty much stop right here. There’s plenty of information on the web that will get you going on an ad-hoc basis, and you can fiddle with it using Notepad and FTP.

Or try modifying a useful little plugin as explained in “How To Customize Estimated Reading Time Plugin for WordPress.” You can make these modifications directly in the WordPress plugin editor. If you mess it up, just delete the plugin and reinstall, no harm, no foul.

However… if you wanna run with the Big Dogs… you gotta get off the porch.

Are you sure you’re ready for this?

Sure you are!

What you need to know

It turns out the programming simple systems such as WordPress plugins is really not that difficult, provided you have the appropiate tools and development environment. In a nutshell, you’ll need to understand a little bit about:

  • Programming language syntax
  • WordPress system operation as a php/mysql web application
  • Network and server operations
  • Programming and development environments

That looks like a lot!

In one sense it is a lot. In another sense, it’s not so bad because you can break it down into independent steps.

From personal experience, and watching many, many other people, your first line of attack is 90% going to be attacking the problem from the syntax level first. Also from long experience, I can tell you that’s a great way to burn yourself out really fast! Instead, start from the bottom of the list above, and get your “workbench” and “tools” squared away first.

Let’s take a closer look at setting up for a home run plugin.

First things first

Now, the very first any programmer worth his or her salt does… is put on some music! A current favorite of mine is Slow Train Soul’s “Illegal Cargo.” If you’re a Hotel Costes fan, you’ve likely heard “In the Black of the Night.” Well, most of the rest of the album is as good as that cut.

Ok, the music is taken care of, for now. Let’s get on with it.

Build your “WAMP” sandbox first

If you’re serious about knocking it out of the ball park, you need to build your own “sandbox.” In computer programming and software development, a sandbox is complete working environment where you can develop new code, experiment and play around with your applications and toolchain without any fear of destroying your product. A sandbox is somewhat like a training field that athletes use for practice before and between games.

Specifically, creating a sandbox means setting up your local computer to act as both a development computer and as a it’s own networked computer. None of this costs any money, but it will cost you some time. Spend that time now, it will pay you back very quickly. I know this because I put this off for 15 years (yes, I was on the web in August 1994).

Plugin sandbox tools

  1. Install a WAMP/LAMP system.
  2. Install a modern IDE like Aptana
  3. Download a few dozen plugins through “Plugin >> Add New.” I recommend Sniplets, Drain Hole, Amazon Reloaded for starters.
  4. Download my WordPress Plugin Starter Kit. My little example plugins will boost your knowledge and productivity tremendously.

Good tools make for easy work

Once you have your sandbox installed, it’s time to consider what sort of programming editor to use. Your choices range from Microsoft’s Notepad, to expensive code editors with more features than anyone could possibly use. I’ve found a nice, middle-ground solution in Aptana Studio. Aptana allows writing and in many cases executing code in a variety of languages including HTML, CSS, PHP and Javascript. Such capability is important in web applications, which often mix several languages in one application.

Aptana is an Eclipse application, which means it shares the same basic functionality and toolkit with Eclipse. Using Aptana gives you leverage if you later want to use Eclipse for Java coding, and vice versa: if you are familiar with Eclipse, Aptana will be easy to use.

Aptana.com has a number of other interesting services, including reasonably priced cloud computing facilities which are not important right now.

Network and server operation

You do not need to know or do much, provided you have a decent host. Once you have your main testing WordPress blog set up on localhost, and can run your final test on your hosted blog (or even better a test blog on your host), WordPress typically makes it pretty easy.

But don’t be afraid to learn as much as you can about server applications such as Apache, Microsoft IIS, MySQL and related technology on your journey to mastery. It will pay you back later when you need to move your blog, fix broken links, create redirections and handle that host of administrative chores that seem to grow with time.

Programming language and syntax

If you have read this far, I’m making the safe assumption you haven’t been scared away yet, and that you’re fairly comfortable with HTML and CSS. Using HTML and CSS is a prerequisite for really digging into WordPress. Fortunately, both are fairly easy to learn. Anyone technically inclined can pick up HTML in a couple of days, and CSS in a couple of weeks. If you haven’t ever hand-coded a web page, you should go do one right now. Do something fancy. Then come back and continue.

As it turns out, PHP is also pretty easy to learn… provided you already understand HTML (the CSS comes in sideways). Again, the best way to learn some PHP is just go code up a simple PHP-driven web page. That should take a day or three, and you will have enough knowledge to dig into reading and writing simple WordPress plugins.

Learning the WordPress Plugin System

The PHP programming language doesn’t have many built-in control on program design, and has garnered a fair amount of contempt over the years as being a language promoting really bad programming. While it’s true that it’s easy to write really awful code in PHP, good software architects can use the strengths of the tool (PHP) to create a programming methodology every bit as robust as can be built with languages with more formal restrictions. And this is what the WordPress programmers have done. The WordPress system is a masterpiece!

The WordPress plugin subsystem is a piece of art… poetry as claimed on wordpress.org.

Once you have learned enough PHP to endanger yourself (that’s a programming joke!), run, don’t walk to purchase Vladimir Prelovac’s “WordPress Plugin Development Beginner’s Guide.”

Now, you need to commit to memory the WordPress definitions of the following terms:

  • event: Something the user does, like save a post, or activate a plugin.
  • action: A function that executes in response to an event.
  • filter: A function that applies itself to WordPress content such as posts and pages.
  • hook: An action function or filter function which is registered with WordPress to be loaded and executed at a precisely defined stage of WordPress execution.

Get these definitions very clear in your head, then go read in more detail about the WordPress Plugin API.

Once you have digested the Plugin API, check out all the excellent tools WordPress gives you for building actions and filters:

After you have read through these documents, you’re ready to take the next step: programming your own plugins!

“Wait!” you say… “It can’t be that easy… I’ve programmed before… you can’t fool me!”

Ok, you’re right, the devil IS in the details… so here are some simple details for you to peruse.

Simple examples demonstrate plugin operation

To make super easy for you to get started programming plugins, I created some very small demonstration examples:

  1. Demo Plugin Paths: PHP has a number of built-in functions for handling paths and file names, which are leveraged by WordPress to handle plugins. In addition, WordPress defines some preset file and path names you need to know to make your plugin programming much more effective. Demo Plugin Paths lists out a set of these… it’s like having an online manual at your fingertips… customized for your own, personal WordPress installation!
  2. Demo Plugin Options: Do your users need to set options? It’s easy and this plugin lays out option setting code, and only option setting code, so you can see exactly how it’s done.
  3. Demo Plugin Database: Do you need a database table? Demo Plugin Database shows you how to add a database table on activation and drop it on deactivation.
  4. Demo Plugin i18n: Make your plugin worldwide using WordPress’s adaptation of the freely available gettext system.

These plugins are currently under development, but you can download Demo Plugin Database right now. Contact me for a current working version of any of the others.

Appendix: Simple SVN for newbies

Once you understand svn checkout, svn update, and svn commit, these three commands here will take your subversion skills to the next level. Actually, it’s not about subversion… learning these three commands will take your software engineering skills up one notch.

  1. svn switch let’s you update your repositories in place.
  2. Branching using svn copy let’s you work on new code, or bug fix old code, in a safe way without destroying previous work.
  3. Merging code changes from svn branch to svn trunk is easy.

Mastering these three commands is simple and will let you leverage your locally hosted WordPress installation fantastically: more programming, less hassle.