Symfony – Standard API for Logging Using __callStatic
Last year I wrote an article on how to write a simple, standard logging class for Symfony (http://melikedev.com/2010/08/25/symfony-standard-api-for-logging/). This article will demonstrate how do to the same functionality in only a few lines of code using __callStatic(). For more info on __callStatic() check out http://melikedev.com/2011/10/31/php-__callstatic-method-overloading/
Before:
// located @ /lib/MyCustom/Api/Log.php
class MyCustom_Api_Log
{
/**
* Wrapper method for getting a symfony logger object
*
* @return object
*/
public static function getLogger()
{
return sfContext::getInstance()->getLogger();
}
/**
* Wrapper method for logging debug message
*
* @param string $message
*/
public static function logDebug($message)
{
self::getLogger()->debug($message);
}
/**
* Wrapper method for logging an error
*
* @param string $message
*/
public static function logError($message)
{
self::getLogger()->err($message);
}
}
// Example Usage
MyCustom_Api_Log::logError('Oh noes something went wrong');
After:
// located @ /lib/MyCustom/Api/Log.php
class MyCustom_Api_Log
{
/**
* Wrapper method for getting a symfony logger object
*
* @return object
*/
public static function getLogger()
{
return sfContext::getInstance()->getLogger();
}
/**
* Magic method for logging all supported log levels
*
* @param string
* @param array
*/
public static function __callStatic($level, $params)
{
// Only concerned with message at this time
// However any number of params can be passed in
$message = shift($params);
self::getLogger()->$level($message);
}
}
// All these calls are made to __callStatic, so no need for individual methods
MyCustom_Api_Log::err(array('Oh noes something went wrong'));
MyCustom_Api_Log::warn(array('Oh noes something went wrong'));
MyCustom_Api_Log::notice(array('Oh noes something went wrong'));
