2011-05-16 41 views
1

我目前正在從我們自己的專有日誌記錄解決方案遷移到log4php。
我們在項目中只使用靜態方法來使用很多類。該文檔定義了基本的使用情況,如:在靜態環境中使用log4php

class MyClass { 
    private $logger; 

    public function __construct() { 
     $this->logger = Logger::getLogger(__CLASS__); 
     $this->logger->debug('currently in constructor'); 
    } 
} 

但我不能使用,因爲我需要在$logger靜態上下文是可用的。製作$logger靜態也沒有幫助,因爲我的類的構造函數從不被調用(因爲它的所有成員都是靜態的)。
該文檔告訴我爲該成員使用靜態初始化器。但是,我必須記得爲所有我使用的課程調用它。這似乎太容易出錯。

於是我想出了這一點:

class Foo { 
    private static $logger = null; 
    private static function logger() { 
    if(null == self::$logger) self::$logger = Logger::getLogger(__CLASS__); 
    return self::$logger; 
    } 

    public static function bar() { 
    self::logger()->debug("test"); 
    } 
} 

Foo::bar(); 

但是,似乎有太多的開銷爲好。那麼,有什麼建議?

回答

0

我想出了一個解決方案,工作得很好,但需要$logger公開。

class Foo { 
    public static $logger = null; 

    public static function bar() { 
    self::$logger->debug("test"); 
    } 
} 

$loggerName = "logger"; 
// Iterate over all declared classes 
$classes = get_declared_classes(); 
foreach($classes as $class) { 
    $reflection = new ReflectionClass($class); 

    // If the class is internally defined by PHP or has no property called "logger", skip it. 
    if($reflection->isInternal() || !$reflection->hasProperty($loggerName)) continue; 

    // Get information regarding the "logger" property of this class. 
    $property = new ReflectionProperty($class, $loggerName); 

    // If the "logger" property is not static or not public, then it is not the one we are interested in. Skip this class. 
    if(!$property->isStatic() || !$property->isPublic()) continue; 

    // Initialize the logger for this class. 
    $reflection->setStaticPropertyValue($loggerName, Logger::getLogger($class)); 
} 

此我只需要定義$logger財產每班一次,運行一次我的初始化代碼(我在我的應用程序的入口點的require_once節過後猜測)。

該代碼的性能影響可以忽略不計,特別是因爲它只運行一次(與我的初始解決方案相比)。這是我一個VirtualBox的虛擬機內測量了英特爾酷Q9450 2.66GHz的@:

10000 iterations for 157 classes completed in 2.6794s. Average per iteration: 0.00026794s 
+0

你的方法有一個很大的缺點:與自動加載,這將無法工作,因爲類後,他們的第一隻宣佈的環境使用。另外,在某處推送記錄器是一種不好的編碼模式。最好讓班級要求並注入。 – Sven 2012-10-12 23:53:05

相關問題