1

私は現在、独自のロギングソリューションから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();

しかし、それもオーバーヘッドが大きすぎるようです。それで、何か提案はありますか?

4

1 に答える 1

0

$logger私は非常にうまく機能するが、公開する必要がある1つの解決策を思いついた。

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 ) );
}

これは、クラスごとに1回プロパティを定義し、初期化コードを1回実行するだけです(アプリケーションのエントリポイントのセクションの$logger後で推測します)。require_once

そのコードのパフォーマンスへの影響はごくわずかです。特に、(最初のソリューションと比較して)1回しか実行されないためです。これは、Intel Core2 Q9450@2.66GHzのVirtualBoxVM内で測定したものです。

10000 iterations for 157 classes completed in 2.6794s. Average per iteration: 0.00026794s
于 2011-05-16T11:16:58.053 に答える