Getting cute or clever has burned everyone. I think that’s safe to say. And yet, there are still those moments when you put something in anyway because, well, it works and it’s elegant.
I’ve been working through error handling recently. I made the decision to build an ErrorHandler class to handle errors and house the code. At some point the thing got sorta longish (500 lines) and I thought up a means to spare the system loading it using a pair of closures.
(This is PHP 5.3+ only)
// Set error and exception handling.
set_error_handler( function($code, $message, $file, $line, $context){
ErrorHandler::setError($code, $message, $file, $line, $context);
});
set_exception_handler( function( \\Exception $e ){
ErrorHandler::exception( $e );
});
Now the error handler logs notices, warnings, stricts and so on and gets firebug to put them in the console. The log is written in the master template (which handles the html head section for nearly all pages) with a single rather cute line.
if ( class_exists('ErrorHandler', false ) ): print(ErrorHandler::getLog()); endif;
So I check if the ErrorHandler got loaded, and if not I don’t load it (hence the rarely used second param to class_exists). If it is present then there must be at least one error. The code is in braceless syntax because all template php in my setup is braceless.
So what cute or clever snippets have you written? Any that came back to bite you??
I tend to shoot for somewhere between clever and stupid. You get to clever an code becomes difficult to manage and come back to at a later date. You make your code stupid and it looks stupid. For example, the dumbest code possible would be all procedural but the advantages of not doing that and organizing the code far out weighs the advantages of just doing everything line by line. Than again you have the people who get to clever and code becomes very difficult to read and follow as it moves from object to object to object, etc to follow some pattern that was essentially forced upon the problem or followed blindly. Its most definitely a tough balance between sacrificing practicality and standards for a more unified whole. The one thing that does help though is comments. When you start to get clever add some comments about why your doing what your doing and you or the person looking at your code in the future will thank you. Really well written code is normally pretty clever and really poor code is normally really stupid. So it is a struggle.
Wait, your error handler uses Firebug, as does FirePHP… but you don’t like FirePHP because it won’t work in all browsers, when neither will your error handler…?
That will also call the functions statically (see here)
Also, if you’ve never heard of it, you may want to take a look at FirePHP. I personally like that a lot better than outputting stuff to the Firebug console. Mostly because you can set levels (warning, error, etc) and it’s possible to create tables.
[/ot]