Categories
Programming & Web Development

PHP Debugging with Xdebug

https://i2.wp.com/xdebug.org/images/xdebug.gif?w=580

Web development with PHP can get frustrating without the adequate tools. The most common thing a new web developer does when attempting PHP debugging is to add var_dump() calls to print out the value of a variable at a certain point in the program’s execution, in conjunction with an exit() or die() call.

Doing this will reveal the values of the variable you’re trying to check, but it requires you to add and remove lines in your code, and more often than not, those lines are forgotten to be removed, so they end up as bugs in the code.

A good way to develop your code is with test driven development, using unit tests to verify the output of your methods. But sometimes there are parts of the code that cannot be easily tested. For these cases using a proper step by step debugger is a better tool for the job. Xdebug is a PHP extension that does the job. With Xdebug you can set breakpoints in your code, display the contents of constants like $_POST and $_SESSION, give you a trace of the execution around the breakpoint or uncaught exception, and follow the values of any variables you want. You can also profile your application to detect performance bottlenecks.

There are several ways to install Xdebug on your development system. On a Debian-based system you install it with the following command:

sudo aptitude install php5-xdebug

For other systems and custom installations there is an installation Wizard, following the steps in the page will provide you with the instructions needed for your particular case.

Then check your php.ini file to configure the Xdebug extension to your liking. Check the documentation for all the features and options. Here’s a sample of the options:

xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.remote_mode=req
xdebug.idekey=default
xdebug.remote_log="/var/log/xdebug/xdebug.log"
xdebug.show_exception_trace=0
xdebug.show_local_vars=9
xdebug.var_display_max_depth=10
xdebug.show_mem_delta=0
xdebug.trace_format=0
xdebug.profiler_enable=1
xdebug.profiler_output_dir="/tmp/xdebug/"

The option xdebug.show_local_vars will display the number of local variables available at the breakpoint, so no need of several var_dump() calls for each variable you want to see. The xdebug.var_display_max_depth changes how many nested levels of arrays or objects will be displayed, where by default, var_dump() will only display 3 levels down. There are more interesting data display options in the documentation.

Make sure the remote log directory and profiler output directories exist in your system. Restart your web server and you’re good to go.

Your phpinfo() output page should now display a section like this:

file:////home/gabriel/xdebug_info.png

Now, here are some links to setup and use your development environment with Xdebug, depending on what you use.

Hope this helps and happy coding!

Categories
GNU/Linux Free Software & Open Source Programming & Web Development

10 PHP code quality tools to avoid a mess in your projects

img_2052

When programming in any language there are certain common errors that everyone makes as they mature and evolve their programming skills. In the case of PHP, I’ve seen a lot of ugly and complicated code around, since the language is very permissive.

To have a good and healthy PHP code base so it won’t resemble the unmanageable cabling mess in the picture above, your project needs to have the following:

– no spaghetti code
– code reuse (avoid code repetition)
– avoid complicated nested loops
– Encapsulation (organize code in classes)
– Clean user I/O
– Code Documentation
– Consistent code conventions
– Tests

Luckily there are some PHP code quality tools that can help us address most of these problems and give us a diagnostic of our project’s code health.

###Documenting your code

PHP Documentor: Documenting code with PHP Documentor is very simple and easy. You just need to follow a very simple markup before your functions and classes and the tool will generate all the developer documentation for you. It’s also very handy when adding new people to your project or inheriting someone else’s work. Just by seeing the documentation comments in the code you can understand what a given function does, what each of its parameters need to be and what it returns. You can also expand the documentation to add use cases and even unit tests!

###Code consistency

PHP Code Sniffer: A tool that analyses the syntax of your project’s code based on a PHP syntax standard. Known standards like PEAR or Zend syntax styles are included by default but you can also customize and define our own team’s style.

PHP Depend
Analyzes the code for common issues and potential optimizations. Some examples of those are:

– if your function is too long
– if your function has too many parameters
– variable names too long or too short
– too many nested cycles
– use of eval()
– name convention consistency
– unused methods or variables

PHP Mess detector: A fork of PHPDepend with a friendlier UI and configuration options

PHPCPD (Copy/Paste Detector): A tool that will detect copy/pasted code across your project that can be reused.

###Testing

Unit testing

PHP Unit and Simpletest: Unit testing has been very useful in my experience on recent projects where I’ve been allowed to implement it. On personal project I always tend to do unit testing before layout out all my code. It might take more time to develop your project at the beginning but it will save you tons of time debugging and tracing back errors when you think you’re done programming.

If you’re using Ubuntu and have problems running PHPUnit, here’s a post about how to solve the problem.

Here’s a quick guide on how to start using Simpletest.

Integration Testing (browser emulation)

Mink and Behat are the tools you’ll need to do browser emulation to test your interfaces and how it’s all put together and interacting for the user.

###Put it all together with Phing

Phing is a tool like GNU Make or Apache Ant but it’s in PHP and extensible via PHP classes. You can put all of these tools together with Phing, so you can automate all the checking, testing and even deployment and cleanup of files or databases.

With these tools you can have a very robust quality assurance workflow on your project. Of course, this doesn’t mean that there’s not going to be any bugs or that your project will have the best code, but at least it will reduce very common problems, will increase code maintainability and help you spot problems easier. The transitions from adding or removing people from the project (like in large teams or dynamic organizations) will be smoother, as well. Also those transitions will be even smoother if you consider using an established web framework for your project instead of writing your own.

I gave a talk at FSL Vallarta 2012 about this, you can download the slides for the talk “Herramientas de calidad en codigo PHP” here. (slides in Spanish)

Categories
GNU/Linux Free Software & Open Source Programming & Web Development

Easy PHP code test development with SimpleTest unit testing framework

Simpletest, Unit Testing for PHP

Testing is a task every developer has to do eventually on any programming project. You can do it manually after writing all your code to see if it works as you intended, or better yet, before writing your code, using test driven development techniques that will save you time and frustrations down the road. One of those techniques is called Unit Testing.

Ideally, unit testing takes place before writing any code. Its a way to plan out how your functions, classes and objects will behave. The basic idea is that you plan the outcomes of each part of your program, then you write those parts to provide that outcome. So think of it as a black box that you will give some input and expect some output. This way you know how objects will be organized, what methods to write in each class, what needs to be their input and how are they going to output the results. Having all your code in tests will help you add new features, change or refactor parts of your code faster without the fear of breaking something else in your software. If you changed something and all your tests still pass, you’re good to go, if not, you can easily track down where the error is and what got affected.

PHP is famous for having spaghetti code and being too flexible that you can mess things out pretty fast, specially when you’re not an experienced programmer, or you have a team of developers with different programming styles and experience working on several components of the same project.

Although there are several unit testing frameworks for PHP, I’ll talk about SimpleTest since its very light, easy to install and easy to learn. Also, if you’re a Drupal developer, its the testing framework of choice.

Setup

To install it, go to the Simpletest download page and get the latest version. Extract the files to your PHP path, or use require_once() calls to the autorun file:

Usage

Here’s an example of a class’ tests (testfile.php):

getList(5);

/* test result is an array */
$this->assertTrue(is_array($result));

/* test correct number of output elements */
$this->assertEqual(count($result), 5);

/* make a different call with different parameter */
$result = $obj->getList();

/* confirm that output is always an array, even with 0 elements */
$this->assertTrue(is_array($result));
}
}

Now you have a basic skeleton of you methods and their behaviors, now you can go ahead and write the real code (myclass.php).

Run it

Once we’ve written the class, we can test out its methods by running our tests script. You can do that by using the command line, or by viewing the php script in a browser window.

Personally, I prefer to use the command line for convenience and faster testing without needing even to setup any web server. Running it will look like this:

$ php testfile.php
testfile.php
OK
Test cases run: 1/1, Passes: 3, Failures: 0, Exceptions: 0

Do more

This is a very small and simple test, but you can also test out the interface of your project. SimpleTest has a browser class that can perform some events like simulating browser visits, doing clicks on your interface’s links and checking the HTML structure of the web server responses.

Check out the full documentation, which is very easily laid out as a big tutorial, and start testing all your code!

Categories
Emacs personal

The Social Network Movie

the social network

I just saw The Social Network movie. From a geeky perspective, its a very interesting movie. But I don’t know if it will be entertaining enough for the general public. Also I say this with the perspective of having read the book, and as most movies based on books, they missed lots of details and changed some events.

The highlights for me, besides the fact that it is interesting to watch the story of a web startup grow, was the more than normal geeky parts. Almost all of the screens of facebook development were using KDE, and Mark Zuckerberg is always shown coding in GNU Emacs. And its the first movie where I ever hear someone say the words “emacs” and “perl script”. Although now that I think about it, why would he use Perl when we all know Facebook is all done on PHP. There was actually some PHP code screens on the movie as well.

social network scene

So if you’re going to see the movie, don’t expect a highly entertaining movie. Its a bit dull and boring at parts with too much dialog going on. But as a friend told me: “what did u expect? a car chase in downtown Palo Alto?”. If you have already seen the movie, I recommend you to read the book The Accidental Billionaires: The Founding of Facebook A Tale of Sex, Money, Genius and Betrayal
to really grasp the details of what is portrayed there. Anyway, nor the book or the movie are completely true, so take it with a grain of salt.

The music by Trent Reznor was great 🙂

Categories
Events GNU/Linux Free Software & Open Source

First day at DrupalCon San Francisco 2010

DrupalCon SF 2010 keynote

DrupalCon San Francisco has been great. Yes, its been only one day but I love the atmosphere.

There are several tracks going on at the same time during the day, so its impossible to see every talk. I hope that they publish videos of the ones I couldn’t attend. There’s about 3,000 attendees so the place is packed.

Drupalcon hallway

I’ve been a bit distant on Drupal development for a while, but its interesting to me to see that most if not all of the talks are about Drupal 7, the next stable release. I guess that the move to this new version is going to be a lot faster than the version 5 to 6 adoption. Yes, it was mainly because many of the cool modules were ported very slowly, but it appears that most of them are going to be ready for the version 7 release.

So for the ones who like me were disconnected from Drupal, here are some of the new features it will have:

– CCK will be in core, called Fields
– Improved usability and accesibilty
– Database connector is now PHP PDO
– Multiple database support
– Testing framework
– RDF support

Here’s a more detailed list of all Drupal 7 features.

There’s no official release yet, but there’s only 114 bugs left and for a big project like this its not so bad. So with enough help that can happen very soon. Get involved and contribute!

Categories
GNU/Linux Free Software & Open Source Interesting random stuff Programming & Web Development

Random links from my bookmarks

I’d like to share my bookmarks from time to time. I think sometimes random browsing can be very fruitful and sometimes even productive.

This week on my delicious bookmaks, I’d like to share:

I hope you find these links interesting or usefull as they’ve been for me.