Return to Snippet

Revision: 28132
at July 1, 2010 22:38 by orenus


Initial Code
///a generic logger...
//polymorphism in action

abstract class ILogger {
	
	protected abstract function writeLog($sSevirity, $sMsg);
}


class Logger implements ILogger{
	
	private static $loggers = array();
	
	protected function writeLog($sSevirity, $sMsg){
		foreach (self::$loggers as $logger){
			$logger->writeLog($sSevirity, $sMsg);
		}
	}
	
	public function registerLogger(ILogger $logger){
		self::$loggers[count(self::$loggers)] = $logger;
	}
	
	public function logDebug($sMsg){
		$this->writeLog("DEBUG", $sMsg);
	}
	
	public function logError($sMsg){
		$this->writeLog("ERROR", $sMsg);
	}
	
	public function logInfo($sMsg){
		$this->writeLog("INFO", $sMsg);
	}
}

abstract class BaseLogger implements ILogger{
	
	private $ipAddr;
	
	public function BaseLogger(){
		Logger::registerLogger($this);
	}
	
	private function getClientIP(){
		//...
	}
}


class MyFileLogger extends BaseLogger{
	
	public function MyFileLogger(){
		parent::__constructor();
	}
	
	protected function writeLog($sSevirity, $sMsg){
		error_log("[". $this->getClientIP() ."] :: ". date("j/n/y H:i:s") . $sSevirity .": ". $sMsg);
	}
} 

class MyDBLogger extends BaseLogger{
	
	public function MyFileLogger(){
		parent::__constructor();
	}
	
	protected function writeLog($sSevirity, $sMsg){
		//connect...
		
		$query = "insert into my_logger (sevirity, message) values ('$sSevirity', '$sMsg')";
		mysql_query($query);
	}
} 



//in use...

$logger = new Logger();

$logger->logDebug("miao");
$logger->logInfo("mitzi");
$logger->logError("pizzi");

Initial URL

                                

Initial Description

                                

Initial Title
Lesson 3 -  Step 3 - Polymorphism in action

Initial Tags

                                

Initial Language
PHP