May Allah`s peace , mercy and blessing be upon you
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 :
- Debugging PHP in browser’s Javascript console
- LETS DEBUG PHP IN BROWSER JS CONSOLE
- Outputting PHP To Browser Console
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 :
<?php
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