NetBeans is an excellent, free IDE (Integrated Development Environment) that is well suited for WordPress website development. Coupled with the free or premium version of DesktopServer and you will have a modern, professional IDE setup. Even if you are already using another editor or development environment like Adobe Dreamweaver (great for design, not so great for debugging), you may still want to give NetBeans a try or use it as your powerful secondary editor. In this post I’ll show you how easy it is to get started and I’ll cover the basics of using NetBeans for WordPress development.

NetBeans IDE

But first, why NetBeans? NetBeans is a mature editor with years of refinement under its belt. While NetBeans is a serious and optimized editor for C++, Java, and PHP coding, beginners will appreciate the straightforward and simple features. Hardcore developers will appreciate the lighter runtime and active community support for PHP (unfortunately, development has stalled for the heavier Eclipse editor for PHP). Since WordPress ‘template tags’ are just PHP functions, NetBeans makes working with WordPress powerful yet elegant. It provides code hinting to predict your needs and help correct your mistakes. For instance, it underlines and changes the font color to make errors obvious. NetBeans tries to understand your code, not just allow you to edit it. A built-in navigation panel allows you to walk through HTML elements, CSS elements, and blocks of PHP code to simplify the critical task of just finding things. Code folding makes reading long complex template documents a breeze by summarizing lines of code into convenient rollovers. This makes it much easier on the eyes (and the brain) by simplifying complex document parts into smaller ‘folded’ excerpts. Given the right key combinations, NetBeans will even write code for you.

Getting Started

To get started, you will want to visit the NetBeans download page at (http://netbeans.org/downloads/index.html) and install the version specific for PHP and your computer platform (support for both Mac and Windows). The installer is typical and straight forward. Simply install using the defaults. After installing NetBeans, take a moment to configure a few more options that will make working with NetBeans even better.

First, make sure you have checked the ‘Enable debug services’ check box in DesktopServer. You can find this setting in DesktopServer’s first main menu option ‘Stop or restart…’. Be sure to select the ‘Restart’ option followed by clicking the ‘Next’ button. Then start NetBeans for the first time and visit the options panel via the pull down menu for your platform: The NetBeans ? Preferences on Mac OS X, or Tools ? Options menu on Windows.
The NetBeans options window will show a number of tabs and sub-tabs. Click the PHP section followed by the Debugging sub tab. You will want to uncheck the ‘Stop at First Line’ check box followed by check marking the ‘Watches and Balloon Evaluation’. You can safely ignore the dialog box that appears regarding stability issues with NetBeans. For the most part, debug services outweigh any stability issues that you might encounter. Most issues that we had were purely aesthetic and rare at that. Click OK to close the window and the options panel.

Import Your Project

If you haven’t already created a project, take a moment to try the simple www.example.dev website as outlined in “Getting Started with DesktopServer”, steps 1 to 10. Importing your existing project into NetBeans is easy. Use NetBeans’ File ? New Project pull down menu to open the New Project dialog. Select the option ‘PHP Application with Existing Sources’, then click the ‘Next’ button to continue.

NetBeans will prompt you for the source folder of your existing WordPress website. Navigate to the root folder by clicking the ‘Browse…’ button and selecting the source folder. Be sure to double-click the source folder (it should contain the wp-content folder). I.e. double-click the www.example.dev folder, followed by clicking the ‘Open’ button. By default, DesktopServer uses PHP 5.3 to match the most common hosting provider configurations found on the Internet today. Be sure to click the drop down combo box for the PHP Version and select PHP 5.3. Click the ‘Next’ button to continue.

DesktopServer will personalize your website project with its own isolated, unique domain name (on top of the fake .dev top-level domain). Be sure to remove the ‘localhost’ in the http://localhost project URL. This will allow you to properly launch, view, and debug your project from NetBeans’ toolbar. In our example, the project URL should simply read http://www.example.dev. Lastly, click the ‘Finish’ button and NetBeans will begin scanning and indexing your website for fast search and project navigation. You will be able to quickly find template files, functions and work on all your website files faster when indexing completes (a progress bar may become visible in the lower right hand side until indexing completes).

Set the main project you are working on by right clicking your project’s domain name and selecting ‘Set as Main Project’ from the pop up context menu. Your selected project will appear in bold. You will want to use the ‘Set as Main Project’ option to take advantage of NetBeans’ exclusive debugging features which we will cover later in this post. Each time you close and then re-open NetBeans, your last open project and any files that you have open will automatically be displayed in the main document editing area. Window positions and any panels that you have sized to your preference will also be restored automatically. You can rearrange and size the window and panels to your liking. To reset the user interface to the default, simply select the Window ? Reset Windows pull down menu.

Editing Features

Get ready to take advantage of some fast, professional development features! NetBeans is a full featured yet free IDE (Integrated Development Environment). But don’t let the free price fool you. It is a powerful environment that rivals expensive editors that cost hundreds of dollars. In many ways, NetBeans performance and features are unparalleled. Now that you have your project open in NetBeans, you will want to familiarize yourself with the editing features. Like most standard text editors, you can use the File and Edit pull down menus to open, close, and edit files. However, NetBeans offers a more powerful way to work with your website files by displaying the ‘Projects’ tab in the upper left hand side. The Projects panel contains a tree structure that shows you all your files and folders. You can easily navigate the tree structure to open a file (via double-click) or copy, rename, create new, or delete files (via a right-click pop-up context menu). Below the Project panel, you’ll find a special Navigator panel that can help you navigate complex template files. Click the image below for a larger view of the index.php file from our example website. Here, we’ve opened our index.php file from WordPress’ default Twenty Eleven theme. This file lives in our example site folder at www.example.dev/wp-content/themes/twentyeleven/index.php. Locate the index.php file using the Project panel and double-click to open it. The Navigator panel should appear revealing HTML elements that are present in the file as an easy to read tree structure.

You can use the Navigator panel to quickly find elements (or PHP functions and classes for code gurus) in your template files. Simply expand the HTML tree branch in the Navigator panel to show the child elements. Double clicking the elements will move the cursor in the code editor area and highlight both the starting and ending tags in yellow. This makes locating broken elements a breeze and traversing unfamiliar theme files easier. If your template pages are feature packed or lengthy, you can give your eyes (and scroll bar) a rest by leveraging “code folding”. Code folding allows you to summarize blocks of code into one line to reduce the complex appearance of your documents. Your complete document is preserved, but the line numbers are literally skipped from view and represented as an excerpt. Leverage code folding by clicking the +/- symbols (to the right of the line numbers, left of your document’s actual code). As a shortcut, you can collapse or expand your entire document at once via the pull down menu View ? Code Folds. This will allow you to drill down and reveal just the pertinent areas of the file you want to focus on or quickly expand your document to show every line number. A convenient rollover feature allows you to peek inside of code folds by simply hovering the mouse pointer over a collapsed region. Code hinting features are very straight forward: just type and NetBeans will pop up suggestions to auto-complete and write code for you. For instance, if you type within the PHP code blocks wp_ and then pause, NetBeans automatically pops up a selective list of WordPress API functions (which begin with wp_). If you desire, you may select from the list using your arrow keys and just press the enter key. Your cursor is automatically positioned within function parameters for you to continue typing along. If you write your own PHP functions, NetBeans will remember them and suggest them within the context of your project. NetBeans actually tries to understand your code and predict your needs.

Search Everything

Search is essential to a powerful editor and NetBeans provides four essential search features. First, the typical in-file search is available (via Ctrl+F on Windows or Command+F on Macintosh). This will help you locate items in the open document, much like any text editor or word processor. Second, you can search within a group of files or within the entire project by right-clicking a folder in the Project panel and selecting ‘Find’ from the pop up context menu. You will be able to quickly search all files within the given folder (and sub folders) for a specific word in an instant. Files matching your search criteria appear in the Search Results panel at the bottom. The Search Results panel displays a convenient list of files with expandable details to show line numbers, cursor positioning and even a little excerpt of where the match exists. Double clicking any of the results immediately opens the file for editing and positions your cursor at the exact location of the successful match. Like in-file search, you can specify case sensitive matching, regular expression pattern matching, and other criteria to help you pinpoint what you are looking for.

NetBeans offers two more search / navigation features specifically for PHP developers. The “Go to Declaration” and “Find Usages” context menus. Simply right-click any PHP function to display the pop up menu. As the name implies, the Go to Declaration menu item will search your entire project for the declaration of a function. This is good for locating items in functions.php or a plugin if your template or plugin development consists of a unwieldy number of files. The complimentary Find Usages menu item conveniently locates everywhere that a given function is being used. In our example image to the right, we’ve opened up the index.php file in WordPress’ default Twenty Eleven theme and right clicked the function “twentyeleven_content_nav”. The function is used to display the content navigation links on the web page. Clicking the Go to Declaration menu will immediately open the functions.php file and position the cursor where the function is defined. Likewise, the Find Usages menu will display a Usages panel which is similar to the Search Results panel when using NetBeans’ Find feature. A list of files, followed by line numbers and quick excerpts displays in the Usages panel allowing the developer to quickly access all the occurrences of where the function is being used. This is especially useful if you have decided to rename something and would like to locate any and all references where the old name is still being used. Search is complimented with a fast and efficient Replace feature should you decide to do bulk renaming across files and folders (accessible via the Edit pull down menu). NetBeans makes searching and navigating a WordPress website’s files fast and easy.

Debugging with NetBeans

This next section covers features for web designers familiar with PHP and for web developers that wish to take their programming skills to the next level. After all, WordPress’ template tags are merely a collection of PHP functions and many designers are already familiar with theme frameworks that leverage hooks and filters. Surprisingly, not all programmers use a debugger as setup is often a challenge. Using DesktopServer with NetBeans eliminates the setup challenge (no need to configure files manually, ports, or install additional software). For those of us that can’t keep all the details in our head or need a hint or just want to know what the hell is going on, the debugger is irreplaceable. While there isn’t enough room in this article to cover the nuances of debugging -much less the fine art of programming patterns for easier debugging, I’ll at least define the debugging process while focusing on the goal of simply introducing this useful DesktopServer + NetBeans feature.

Debugging Briefly Defined

To understand the debugger, we first need to cover programming fundamentals: you write instructions like musical notes, and the computer plays them back like a musician reading a score. This analogy could be extended to a needle on a record (remember those?), playing back the recorded musical notes as the record spins. When you alter template files (or any .php files), you are changing the musical notes that are ‘played back’ when the web page loads. For the most part, musical notes are read in order like a book, line by line from top to bottom. Things get complicated when we introduce conditionals (‘if’ and ‘switch’ statements) that can change the position of the needle on the record or line number, or even the current page where we are reading those musical notes. This is where the NetBeans debugger can really help: by stopping the needle on the record and keeping the record from spinning (until we want it too). We are allowed to review the musical notes that have already been played and future notes that are about to be played. By tracing the flow of instructions (‘notes’), we can understand where we are going and how we got there. Which is helpful if we are not seeing what we expected, or if we are just plain lost. As a bonus, the debugger also keeps a journal of where we’ve been and a powerful watch tool to help us if we are out-of-tune or off-key, so to speak.

Starting the Debugger

So let’s get started! First, you will want to begin by creating a ‘breakpoint’. A breakpoint is simply a location in our PHP file that defines a line number where we want to pause execution (or in our record player analogy, stop the needle from playing more musical notes). Setting a breakpoint is easy, just click the line number that contains PHP code and the entire line will change from a white background to red. The red line is an indicator of a breakpoint. To follow along with the image to the left, open WordPress’ default Twenty Eleven theme folder and create a breakpoint on line number 22 of the index.php file (i.e., at /wp-content/themes/twentyeleven/index.php). Second, click the ‘Debug Main Project’ button on the toolbar. This button appears to the right of the green arrow icon. The green arrow button is also known as the ‘Run Main Project’ button, which only starts your default web browser (if it isn’t opened already) and visits your site’s homepage. No big deal there. You could have just as easily opened your web browser and typed in the URL to your website. The second button is much more important: ‘Debug Main Project’ because it changes NetBeans from an editor to a debugger.

Once in debug mode, the extra debug buttons will appear on the toolbar and your default web browser will open. Your browser will appear as if it is loading forever (this is because we’ve paused the record). Switch your focus back to NetBeans and you will notice that the editor is in debug mode. The additional ‘step’ icon buttons should appear along with a green line where the red line for our breakpoint formerly resided. The green line represents the ‘instruction pointer’ (or needle in our record player analogy) showing us the next line of code to be run. You’ve now stopped on your first breakpoint and can try to inspect what WordPress is doing internally, such as variable values and the call stack (the journal or where we have been). With NetBeans in debug mode, look for the Variables panel. By default, the Variables panel should appear as a tab at the bottom of NetBeans’ main editor window. Follow through with step 4 (as shown in the image above) and right-click within the Variables panel and select ‘New Watch…’ from the context pop-up menu. A dialog box should appear allowing you to type in a variable to inspect the contents. In our example, we typed in the global $post variable to see the current post being accessed in WordPress. The Variables panel will update and show us the variable contents. Since the $post variable is actually an object containing other public PHP properties, it will appear as a tree structure that you can click to further expand and see its contents. You can remove the variable by right-clicking $post in the list and selecting ‘Delete’ from the pop up context menu.

You can only inspect variable contents while the instruction pointer is paused on a breakpoint. Your web browser may appear blank or to have stalled, waiting for the rest of the webpage to load. To complete the webpage loading (or continue our record playing music analogy), click the Continue button. The Continue button appears as the green circle with a right facing arrow to the right of the Debug Main Project button. NetBeans will finish transmitting the entire webpage to your browser and the page should render. Using the Continue button does not stop NetBeans’ debug mode. If you click ‘reload’ on your web browser or type the URL to a web page that stumbles across the same breakpoint, the instruction pointer (record player needle) will pause playback on the same breakpoint. Your webpage will appear loading indefinitely and you can inspect variable values again or click Continue to resume playback. To switch back to editing your documents and exit NetBeans’ debug mode, use the Stop Debug button. Stop appears as a red square with a white center and returns NetBeans to editor mode. Editor mode is where you can safely make changes and see them reflected the next time you visit your web pages or start the debug process again. So far we’ve covered the first four buttons on the debugger toolbar:
  1. Run Main Project – simply open your default web browser and visit your WordPress’ home page. For the most part, we can ignore this button.
  2. Debug Main Project – Put NetBeans into debug mode while also opening up your web browser to visit your WordPress’ home page, but stop on any pre-defined breakpoints. This is our most important button.
  3. Finish Debugger (a.k.a. Stop) – Stops the debugging process and puts NetBeans back into editor mode, allowing you to safely make edits to your documents.
  4. Continue – Continue debugging and stopping on the next pre-defined breakpoints (if any).
Going Step By Step

The additional step buttons on the tool bar are equally important to debugging and each restarts then pauses the playback of our ‘record player’ but with subtle differences. To understand the differences, we need to go back to our basic programming fundamentals again: PHP code is often written in titled paragraphs (known as functions) that are re-played by simply referring to the paragraph title (the function name). Calling the function by name repeatedly allows PHP programmers to invoke the same paragraph of behavior without having to re-write the entire paragraph over and over. In fact, most of WordPress is simply functions that call other functions and so on. Keep in mind that those function definitions may exist in other PHP files throughout your WordPress project. For convenience, the NetBeans debugger provides the Step Over button as the first step button on the toolbar, just to the right of the Continue button. Pressing the Step Over button will advance to the next line of PHP code (usually in the current file you are viewing). Step Over will skip jumping to other functions and stepping through their lines of code (and avoids opening up the other files containing function definitions). The lines of code for the called functions still get processed (as with all the debugger buttons), but we just don’t have to go through every line of code and open all their associated files, which can quickly become cumbersome.

In contrast to the Step Over button is the Step Into button. Unlike Step Over, Step Into will show us every line of PHP code the instruction pointer processes. The button will ‘Step Into’ every function definition’s lines of code. If a function is defined in another file and is not a native PHP function (PHP’s basic built-in vocabulary), the Step Into button will automatically open and load the file where the function lives and place the instruction pointer on the first line within the function definition. More often than not, functions usually call other functions, which call other functions, and so on. With function definitions spread across multiple files, things can get complicated rather quickly.

Thankfully, NetBeans provides another window panel to help sort out called functions and their files: the Call Stack. By default, the Call Stack appears while NetBeans is in debug mode just below the main editor window as a tab next to the Variables panel. It is like a journal that shows us a list of files loaded along the way to our breakpoint. The Call Stack shows listings such as plugin files that loaded and their processed order. The list is similar to the browser history of clicked hyperlinks in your web browser. Ever wanted to know which plugin files are loaded first or at all? Check the Call Stack. You can double-click any of the entries in the Call Stack list and the given PHP file will open and the cursor will automatically be placed on the last line number that the file processed before calling another PHP function in another PHP file.

The second to last button in the debug toolbar group is the Step Out button. It provides a convenient way to ‘Step Out’ of the current child function and pause immediately within the parent calling function. It acts like the back button on your web browser by taking you back to the original calling function. Lastly, there is the Run to Cursor button. As the name implies, this button works like the Continue button by letting the instruction pointer progress to where ever our blinking cursor is positioned before pausing again. You can use the Run to Cursor button by placing the cursor on a line ahead of the instruction pointer’s current green line (the line must contain valid PHP code). After placing the blinking cursor on another line, press the Run to Cursor button and the instruction pointer will advance until it reaches the blinking cursor. If the cursor does not contain PHP that the instruction pointer will pass through, the effect is the same as the Continue button. The Run to Cursor button is great for stepping through multiple lines of code to reach what you consider is important to walk through. It also makes cycling through loops easier. As we mentioned earlier, the computer reads our PHP scripts much like a musician reads music note by note, line by line. Repeatable lines of music sometimes accompany music scores in the form of ‘repeat barlines’ and ‘volta brackets’. Don’t worry if you are not familiar with music scores. As a developer, you should simply know that PHP includes special statements for loops, and conditionals (‘if’, ‘switch’, ‘while’, ‘for…’, etc.) that influence which lines of code get processed next. One of the most important loops that you should familiarize yourself with is the post loop (a.k.a. The Loop in the official codex). You can use the step buttons to follow the instruction pointer along and see how loops get processed and how the instruction pointer moves through files which can help you find problem areas.

Debugging Tips

Here are some tips that can help make working with the debugger easier.

  • You can only create breakpoints on lines that contain PHP code. If you would like to create a breakpoint on an arbitrary line, you can always try placing a non-trivial PHP code block to set a breakpoint on a line, such as: <?php $x = 1; ?> followed by clicking the line number to set the breakpoint.
  • Keep in mind that you can create breakpoints even during debug mode. If you step past a line of interest, simply go back and click the line number to create a breakpoint. You can then restart debug mode by using the Stop and Debug Main Project buttons.
  • Running in debug mode is slower than simply visiting the website with the debugger stopped because NetBeans must gather extra data. However, you can still gauge relatively slow parts of your program (or plugins) by setting multiple breakpoints and using the Continue button to estimate the length of time before breakpoints turn from red to green.
  • Breakpoints are preserved even after you close and re-open files. To clear all breakpoints in a given project, use the Breakpoints window panel that is accessible via Ctrl+Shift+5 or via the pull down menu:
    Window ? Debugging ? Breakpoints.
  • You can add a variable to the Variables panel quickly by simply placing the cursor on the variable and pressing Shift+Ctrl+F7 on Windows or Shift+Command+F7 on Macintosh. You can also right-click and select ‘New Watch’ to watch the variable contents in the Variables window panel.
  • WordPress has dozens of global variables (see http://codex.wordpress.org/Global_Variables) that you can use and examine. In some cases, you may need to prepend the ‘global’ statement to gain access. For instance, choose a location for your breakpoint and prepend the PHP block  before the breakpoint and you will be able to add the $wp variable to your Variables panel to view its contents.
  • Some WordPress template tags and functions have return values, while others echo them out to the display. Often times there is a return value equivalent of the same function or an option parameter that you can pass to get a return value (i.e. see wp_list_categories ‘echo’ parameter). Casting a return value into a variable can assist in viewing the contents in the Variables panel. You could cast a return value from a function into a variable such as $x = get_bloginfo(‘name’); (versus using the echoing version of the same function bloginfo(‘name’); ) to find out the value.
  • For additional information specific to NetBeans debugging with PHP, see Debugging PHP Source Code in the NetBeans IDE at http://netbeans.org/kb/docs/php/debugging.html.
If you can master the art of basic debugging, you do not need to know everything about the a program to change, hack, or morph code to your needs. Debugging reveals to you the working internals of everything, much like a microscope can show structors of a larger component. You’ll be able to decipher the characteristics and behavior of an application based on its fundamental pieces and know which functions are being used. Most importantly, the debugger can reveal why something is happening or NOT happening such as when a condition is not being met. You won’t need to know everything about a program’s design or even programming design patterns and methodologies to start working with the debugger. Debugging takes a lower level approach and will allow you to see under WordPress’ hood and watch how the program makes decisions and outputs various portions of your template files or, just as importantly, why it does not.

Conclusion

NetBeans is a free yet elegant code editor that supports powerful features often reserved for expensive commercial products such as code folding, a code navigator, and project manager. It tries to understand your code by providing predictive code hints and highlighting errors. NetBeans also includes important search features that support selective pattern matching, advanced regular expressions, and search & replace (either globally, locally or with a custom filter). When coupled with DesktopServer, NetBeans provides a strong debugging tool. However, we have only scratched the surface of NetBeans as there are many more powerful features that we have not covered: such as Git/SVN/other source code integration, differencing, unit testing, code profiling, refactoring and MySQL integration to name a few. NetBeans can scale well for beginning development professionals to seasoned development masters and is able to assist you more and more as your skill level improves and project needs increase. For instance, you may wish to add WordPress specific templates to NetBeans or leverage NetBeans’ plugin repository to make PHP documentation one click away. The amazing NetBeans IDE is free, fast, lightweight, and even easier to use when coupled with either the free or premium version of DesktopServer. NetBeans is well worth the download even if you only use a fraction of its features. Give it a try!

Tagged , , , , ,
About Stephen Carnam
I’m a San Diego, California based computer programmer and graphic designer that has been consulting, developing, and maintaining web & software applications for well over ten years. My languages and interests include PHP, Java, JavaScript, 3D rendering/sculpting, and snow boarding.

6 Comments

  1. codersteve says:

    Hi Stephen,

    Thank you for this super article! I especially found the “Debugging with NetBeans” discussion very helpful. And yes, DesktopServer makes it so much easier than dealing with manual set up of XAMPP and XDEBUG!

    Thank you for recommending NetBeans – I’ve just uninstalled Eclipse :)

    Thank you,
    Steve

  2. solari says:

    Great stuff. What about versioning and the like? Often I need to modify templates I’ve purchased and when they issue updates I need to be able to track the changes I’ve made and integrate in the new updates. What’s the best/easiest practice for something like this? Thanks!

    Ray

    1. Stephen Carroll says:

      Hello Ray,
      Since DesktopServer works like a real web server, you can obtain updates if your theme author implements an update mechanism. However, you’d most like use WordPress’ native child theming behavior so that you can just update the parent theme w/out affecting your modifications. Otherwise, you may wish to look into NetBeans’ native Dif tool that is built into the Tools pull down menu. It will show you changes and modifications between your currently open file and another of your choosing. The interface is full featured and very powerful.

      Regards,
      Stephen

  3. sph750 says:

    great, thanks you for this article

  4. sph750 says:

    Hi Stephen,
    Great Job. I would like to add phpunit, is it easy too ?

    1. Stephen Carroll says:

      Haven’t tried it ourselves but, I’ve added it to the “to do” list! :-)

Leave a Reply

You must be logged in to post a comment.