Should I use one class or more?
In my PHP web application, I want to have the ability to perform the following logging operations:
- Write a database record to an 'error_log' table.
- Write a database record to a 'history_log' table.
- Log all queries to the Firebug console via FirePHP.
- 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)
- class FirebugConsoleLogger
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)
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.
精彩评论