Thursday, September 6, 2012

PHPLogger: Debugging PHP in console

May Allah`s peace , mercy and blessing be upon you

Yesterday, I got nostalgic about PHP because recently I used too much JavaScript and some Python, and what these two have in common is real easy debugging beside coolness . Back to PHP days I didn't care about debugging because I was a beginner - and still :P - , so I was satisfied with the old tricks echo, print_r , var_dump, die ... - etc Like if there is many :) - .

Debugging PHP really sucks , I know that PHP fans will be furbishing their swords already and start praising their tools but additional software like Xdebug is not practical when used outside IDE. I hate to get confused by windows so I use only two : Browser/Editor or Terminal/Editor. Therefore, using other terminal(s) to debug makes me discomfortable.

Browser's console is the most awesome debugging tool: No more layout destruction, no more log file which needs refresh every time and no more unreadable output. So why not using it for PHP too, FirePHP is a good choice but I found implementations that uses PHP to output JavaScript code that use console to log :

Inspired by these codes I tried to write my own , actually I didn't like the fact that all those function can log one variable at once and always need extra arguments to specify type , which means I would use the func_get_args to make it multi-arguments. But first console has 4 methods : log , warn , info , error . The only difference is the name so the use of method overloading __call($name, $arguments) is appropriate , the benefit is that we already got the arguments so no need to use func_get_args and no need to specify type.
What's left is conversions :
  • Strings needs quotes.
  • Objects and arrays are JSON encoded.
  • Booleans get transformed to text.

The code :
class console {
     function __call($name, $args) {
         if(!in_array($name, array("error","log","info","warn"))) return;
         echo '<script type="text/javascript">';
         $log = "";
         foreach($args as $var) {
             if (is_object($var) || is_array($var)) $log .= json_encode($var).",";
             elseif (is_string($var)) $log .= '"'.$var.'",';
             elseif (is_bool($var)) $log .= ($var)?"true,":"false,";
             else $log .= $var.",";
         $log = substr($log, 0,-1);
         echo "console.$name(".$log.");";
         echo '</script>';
//Add an instance but needs "global" when called from functions
$console = new console();
And here is the repo on Github , enjoy !!

No comments:

Post a Comment

Zoli Issam's blog proudly powered by Blogger | All rights reserved Jaw,B 2010-2013