My home-made simple logger (just a wrapper around fopen, fwrite, fclose) should be enabled or disabled on the fly. I think the way i’m checking if logging is enable is overkill (every call to a logging method requires to evaluate LOGGING):
config.inc.php
define('LOGGING', true);
logger.php
public function __construct($filename)
{
$this->fp = fopen($filename, 'w+');
}
public function __destruct()
{
fclose($this->fp);
}
public function warn($message)
{
$this->log('WARN', $message);
}
private function log($type, $message)
{
if(!defined(LOGGING) || !LOGGING) return;
fwrite($this->fp, "[$type] $message\n");
}
Question: how to initialize file handler to something like null and remove the check for LOGGING? I mean something like this:
public function __construct($filename)
{
// Create a fake stream if logging is disabled
$this->fp = !defined(LOGGING) || !LOGGING ? null : fopen($filename, 'w+);
}
Future call to $logger->warn('Ops..') should do nothing, without triggering any error or notice.
I mentioned it as a comment above. However, now once again as an answer, because now I think it is one.
You can create a special logger subclass, something like
When
LOGGINGisfalse, just use this log class and every call with just doing nothing, what will reduce the overhead to the absolute minimum.This approach has even an own name/pattern: http://en.wikipedia.org/wiki/Null_Object_pattern