On many of my websites, I use a homemade PHP class called "Logger" (basically, it's intended for logging informations into log files, and organizing these files by date : year/month... automatically).
I'm using it by creating an instance of Logger in my bootstrap file (included everywhere) :
require 'lib/Logger.class.php';
$mainLogger = new Logger('./my_log_folder');
This forces me to set $mainLogger
global in every function that need to log something, and also check if the logger is instantiated before call to any method :
function foo($bar){
global $mainLogger;
if( !is_null($mainLogger) ){
// If the logger is instanciated, I can log my message
$mainLogger->log('error', 'mysql-errors', "My error message lorem ipsum dolor sit amet", Logger::GRAN_MONTH);
}
}
To make this tool easier to use and write less code, I was thinking about creating a function (outside of Logger class) that handles the instanciation and retrieval of the $mainLogger
(something close to singleton design pattern) :
function getLogger(){
global $mainLogger;
if( !isset($mainLogger) ){
if( class_exists('Logger') ){
// Instanciation of the main logger
$mainLogger = new Logger('./my_log_folder');
} else {
// The Logger class doesn't exists, so we'll return a magical object to "mimic" the logger attributes & methods, thus avoiding fatal errors
return new MagicalClass();
}
}
return $mainLogger;
}
class MagicalClass {
public function __get($name){
return;
}
public function __call($name, $args){
return $this; // Allow to chain calls to this class, like jQuery : getLogger->foo()->bar()...
}
}
The MagicalClass is intended to avoid fatal errors (Fatal error: Call to undefined method...) that could raise by calling this for example (without Logger.class.php included) :
getLogger->log('error', 'mysql-errors', "My error message lorem ipsum dolor sit amet", Logger::GRAN_MONTH);
Thanks to _call and _get, any attempt to use attributes or methods of the Logger class will not cause any error (error logging is an optional feature, it shouldn't crash the app simply if the Logger doesn't exists).
What do you think about this approach, is it a bad idea ? Can this lead me to some troubles, and what kind ?
Thanks
PS : If you want to see the Logger class, you can download it on my website here.