Xdebug will make you a better PHP developer

There are two epochs in my life as a PHP developer: pre-Xdebug and post-Xdebug. Before I actually used Xdebug, I relied on var_dump() and my wit alone to navigate through my troubleshooting and debugging processes. I thought that Xdebug merely provided a fancy display for var_dump()‘d code… and who needs that? Needless to say, Xdebug provides far more than just fancy markup for dumped variables; and it didn’t take long (though longer than I would have liked) in my growth as a developer to understand its true value.

Xdebug actually does make your var_dumps way easier to read (not that you will need to be dumping variables any longer)
Xdebug actually does make your var_dumps way easier to read (not that you will need to be frequently dumping variables any longer)

This post is for those PHP developers out there who either have little-to-no experience with Xdebug and/or those who just haven’t taken the time to learn how to use it/set it up/etc. I will provide you with some material to get you started on your path to Xdebug mastery as well as provide a few examples of how Xdebug has helped me quickly overcome and learn from debugging/troubleshooting sessions that were hitherto a complete PITA (and time-consuming to boot).

Debugging

In programming, debugging is a method or set of methods used by a developer to find and eliminate code that is not appropriately producing an expected result. Everyone has their own approach, it seems, but I am certain we have all at some point fallen into inadvisable debugging practices. There comes a time in every developer’s life when they must dive a little more deeply into some set of third-party code (WordPress core, for example) in order to fully understand why their code isn’t producing expected results. Take for example this method of debugging (of which we are all undoubtedly guilty of using):

/** 
 * Let's say we just want to get 5 posts from our database, 
 * and echo out their IDs. We might do something like this:
 */
$args = array(
            'post_type'        => 'postt', // let's pretend we are not aware of this typo
            'posts_per_page'   => 5,
            'suppress_filters' => false,
        );
$posts = get_posts( $args );

if ( ! empty( $posts ) ) {
    foreach ( $posts as $post ) {
        /** 
         * we are not seeing the IDs echo'd on the front end 
         * and begin to wonder why...
         */
        echo intval( $post->ID );
    }
}

/**
 * Assuming that we don't know about the typo above,
 * carefully reading through the code that executed in order to 
 * produce this broken result is, more often than not, an impractical
 * endeavor. Instead, we find it easier to dump out the variable holding 
 * the data that is not producing expected results using var_dump()
 * right in our code base.
 */
var_dump( $posts );

That instance of var_dump( $posts ) is known as “debug code”. Using debug code should be generally avoided if at all possible and should only be used as a last resort. (Unfortunately, in some situations, using debug code is the only option we have at our fingertips – in these situations, it is important that we become very attentive in our use of debug code.) The greatest threat that debug code poses to a codebase is that it could potentially find its way into production code – which can lead not only to an ugly front-end and more time spent debugging your debug code, but also to graver circumstances, like security vulnerabilities.

Using debug code should be generally avoided if at all possible and should only be used as a last resort.

Getting Acquainted with Xdebug

For those who don’t know, Xdebug is a PHP extension that provides developers with a very powerful debugger and profiler. It supports stack and function traces, profiling information, memory allocation and script execution analysis. In other words, it grants us access to fully understand, experiment with and dig through the entire scope of a PHP application (for example, a WordPress installation) at and/or from any given line during the application’s execution (for example a page load) – all without changing a single line of our code base.

Installing Xdebug

I am going to forgo the effort of rewriting Xdebug’s installation steps; you can, however, refer to the github repo for basic installation support. For those of you who use VVV for local development: good news! Xdebug comes pre-packaged, all you need to do is activate it by following these steps. If you are totally lost and would like additional help, feel free to email me. I can’t promise a quick turn around, but I am willing to help whenever possible.

Configuring Xdebug

Once Xdebug is installed on your development environment, pretty much the only thing left to do is to configure your IDE or code editor. There are as many different ways to configure/set up Xdebug as there are code editors. There are plenty of tutorials for the various popular IDEs and editors out there, so again I will refrain from re-documenting what so many others have already done for us. Below is a list of links to Xdebug configurations demos for various editors.

Understanding Xdebug

Hopefully, you were able to get to this point without too much trouble (I assure you that whatever effort you spend getting Xdebug installed and configured is well worth it). Before jumping in, we should familiarize ourselves with some important Xdebug jargon. Understanding how to use Xdebug relies primarily on understanding 4 of its main terms and 4 of it’s main functions:

Terms:

  • Breakpoints: User selected lines in your code that will suspend the execution of you application.
  • Context: The complete state of your application (all of the variables and expressions that exist at the moment of the breakpoint).
  • Watch: User defined set of variables to watch throughout the execution of the application.
  • Stack Trace: The file trajectory that the application took to arrive at the breakpoint.

Functions:

  • Step Over: Goes to the next PHP line in current file. Does not go into method calls made within current context.
  • Step Into: Goes to the next PHP line in current execution, not just the file. Dives into any method calls made, giving far more detail than Step Over. (Particularly useful for tracking functions that get passed to actions and filters.)
  • Step Out: Step out of the current function.
  • Run: Finish executing the script, skipping over any breakpoints.

Using Xdebug

Using Xdebug is actually quite simple. The typical workflow goes something like this:

  1. Set a “breakpoint” at a specific line in your PHP code (where php is being executed).
  2. Launch your browser on an URL that will fire the code on the line with the breakpoint. (Xdebug should stop the execution at the breakpoint.)
  3. View the variables at the moment of the application’s execution, use the console, view the stack trace, etc to find any odd behavior/properties/variables.
xdebug_breakpoint
PHPStorm’s Xdebug UI showing a successfully halted application at a breakpoint set at line 67
xdebug_breakpoint_variables
PHPStorm’s Xdebug UI showing a map of a given variable (an array in this case) at the breakpoint at line 67

As you can see, not only is this is a far less invasive method for debugging than writing debug code, it also offers you a very wide scope of information about the application you are working with at a given point in its execution (especially some aspect of the application that you didn’t know you needed to look for until you halted the application and snooped around). I greatly urge you to become efficient working with Xdebug as it will speed up your development process, it will give you a more holistic understanding of the objects you are working with, and it will make debugging a breeze for some of the most difficult problems you can encounter (in the future, I plan on posting Xdebug tips and tricks for debugging complications that WordPress devs might frequently run into).

Cheers!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *