Should I use one class or more?

61 Views Asked by At

In my PHP web application, I want to have the ability to perform the following logging operations:

  1. Write a database record to an 'error_log' table.
  2. Write a database record to a 'history_log' table.
  3. Log all queries to the Firebug console via FirePHP.
  4. Log any arbitrary data to the Firebug console using FirePHP.

I am trying to decide on the better achitecture. I have two in mind. Which of these is the better one? I'm open to others as well.

Design #1

  • abstract class Logger
    • class FirebugConsoleLogger
      • getInstance()
      • log(string)
    • class DatabaseLogger
      • getInstance()
      • logError(logTypeId, affiliateId, detailsArray)
      • logHistory(logTypeId, affiliateId, detailsArray)

Design #2

  • class Logger
  • getInstance()
  • logToFirebugConsole(string)
  • logError(string)
  • logHistory(string)

EDIT Here's what I'm probably going to go with.

  • class FirebugConsoleLogger
    • public getInstance()
    • public log(string)
  • abstract class Logger
    • abstract public log(typeId, affiliateId, details)
    • class ErrorLogger
      • public getInstance()
      • public log(typeId, affiliateId, details)
    • class HistoryLogger
      • public getInstance()
      • public log(typeId, affiliateId, details)
1

There are 1 best solutions below

2
On BEST ANSWER

I would use neither. I'd use a design that implements the same log method for each implementation. So it looks like Design #1, but a little different.

  • abstract class Logger
    • log(string)

Create descendants for each type of log you have and override the log method.

Then, create a factory for specific purposes, so:

  • class QueryLoggerFactory
    • getInstance() // Returns a/the FireBugConsoleLogger instance
  • class ErrorLoggerFactory
    • getInstance() // Returns a database logger instance
  • class HistoryLoggerFactory
    • getInstance() // Returns same or different database logger instance

That way, when you need to log a query, you just call

QueryLoggerFactory->getInstance()->log($query);

And nowhere in your application you need to call a specific method. If you decide you want to store the query in the database too, you just instantiate a different logger in your factory. You can even instantiate a logger that logs itself to two other loggers, so you can store errors in FireBug and in the database. Or you can instantiate a void logger that doesn't log anything.