Frage

I'm looking for a better solution to the one below.

I want to start logging from a main script which calls multiple classes to carry out various tasks. I want all called classes to share the logging instance and add messages to the log.

For example:

Main Script:

<?php

include 'log.php'
include 'classA.php'
include 'classB.php'

// start new logs
$log = new log('my_log_file.log');
$log->addMessage('log added outside any classes');

// continue loggin within other classes

$task_a = new classA($log);

$task_b = new classB($log);

classA:

<?php

class classA {

function __construct($log="") {

  if(is_object($log)) {
    $log->AddMessage("log added from within classA");
  }

}

}

What's a better way to do this?

War es hilfreich?

Lösung 2

Some nice responses folks, thanks for that. For my requirements, I'm sticking with what I originally have as nothing else proposed better matched what I already have.

Andere Tipps

You could think about creating Registry class and put object of log to them

<?php

include 'registry.php';
include 'log.php';
include 'classA.php';
include 'classB.php';

// start new logs
$registry = new registry();
$registry->addLogger(new log('my_log_file.log'));
$registry->getLogger->addMessage('log added outside any classes');

// continue loggin within other classes

$task_a = new classA($registry);

$task_b = new classB($registry);

class a.php

<?php

class classA {

function __construct($registry="") {

  if(is_object($registry)) {
    $registry->getLogger()->AddMessage("log added from within classA");
  }

}

}

What's the gain? If you decide you need to pass to other classes other objects as for example database connection, application configuration or others, you simple modify registry, add to registry new object (for example addDatabase) and you'll be able to have database connection in all classes that you've passed Registry object.

Of course you can for some classes object pass only selected registry objects not the whole registry

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top