Tuesday, February 3, 2009

Enhancing CakePHP's debug() function for null, false, and empty string

CakePHP's debug() function is great. Aside from printing out the variable content, it also displays from which line it is called. If you call out debug() in different places, knowing which line saves a lot of time tracking something.

What bothers me sometimes is it doesn't tell you if the variable is NULL, false, or an empty string, so I end up using var_dump() to double check. So how to fix this? Right! We'll edit something inside the cake folder ;) This is usually bad practice but this is a safe one (we'll just plug something in.. kinda), and it won't break your stuff in case you upgrade your cake library. Here you go:

Add this function at the bottom of app/config/core.php:
# this prints out booleans, nulls, and empty strings
# will be called inside cake's debug() on cake/basics.php
function debug2($var)
{
if(is_null($var) || is_bool($var))
{
var_dump($var);
}
else if( is_string($var) )
{
if( '' == trim($var) )
{
var_dump($var);
}
}
}
Here's the dirty part! open cake/basics.php and find the debug() function (line ~104). Add this code before print_r is called: (only the bold part)

if(function_exists('debug2')) {
debug2($var);
}
$var = print_r($var, true);

Now when you call debug(NULL), it will now look like this:
app\app_controller.php (line 72)
NULL

Have fun baking!

No comments:

Post a Comment