Lesson 3 - Step 3 - Polymorphism in action


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. ///a generic logger...
  2. //polymorphism in action
  3.  
  4. abstract class ILogger {
  5.  
  6. protected abstract function writeLog($sSevirity, $sMsg);
  7. }
  8.  
  9.  
  10. class Logger implements ILogger{
  11.  
  12. private static $loggers = array();
  13.  
  14. protected function writeLog($sSevirity, $sMsg){
  15. foreach (self::$loggers as $logger){
  16. $logger->writeLog($sSevirity, $sMsg);
  17. }
  18. }
  19.  
  20. public function registerLogger(ILogger $logger){
  21. self::$loggers[count(self::$loggers)] = $logger;
  22. }
  23.  
  24. public function logDebug($sMsg){
  25. $this->writeLog("DEBUG", $sMsg);
  26. }
  27.  
  28. public function logError($sMsg){
  29. $this->writeLog("ERROR", $sMsg);
  30. }
  31.  
  32. public function logInfo($sMsg){
  33. $this->writeLog("INFO", $sMsg);
  34. }
  35. }
  36.  
  37. abstract class BaseLogger implements ILogger{
  38.  
  39. private $ipAddr;
  40.  
  41. public function BaseLogger(){
  42. Logger::registerLogger($this);
  43. }
  44.  
  45. private function getClientIP(){
  46. //...
  47. }
  48. }
  49.  
  50.  
  51. class MyFileLogger extends BaseLogger{
  52.  
  53. public function MyFileLogger(){
  54. parent::__constructor();
  55. }
  56.  
  57. protected function writeLog($sSevirity, $sMsg){
  58. error_log("[". $this->getClientIP() ."] :: ". date("j/n/y H:i:s") . $sSevirity .": ". $sMsg);
  59. }
  60. }
  61.  
  62. class MyDBLogger extends BaseLogger{
  63.  
  64. public function MyFileLogger(){
  65. parent::__constructor();
  66. }
  67.  
  68. protected function writeLog($sSevirity, $sMsg){
  69. //connect...
  70.  
  71. $query = "insert into my_logger (sevirity, message) values ('$sSevirity', '$sMsg')";
  72. mysql_query($query);
  73. }
  74. }
  75.  
  76.  
  77.  
  78. //in use...
  79.  
  80. $logger = new Logger();
  81.  
  82. $logger->logDebug("miao");
  83. $logger->logInfo("mitzi");
  84. $logger->logError("pizzi");

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.