Question

I'm looking into the SplObserver pattern as a way of solving the logging problem (namely how do you handle activity logging without implementing it directly in the classes you're interested in and therefore putting code in them that isn't directly related to their area of responsibility).

The problem is that as implemented, SplObserver doesn't seem to give you any kind of standardized mechanism for the notifying class to send any details to the observing class other than "I'm triggering a notification".

I was curious as to how other people get around this problem, do they extend the SplObserver and SplSubject interfaces or roll their own instead?

I was also thinking that in more general terms (as in other functionality that could be implemented with Observers, not necessarially logging) if it was possible to implement an Observer pattern where the observer can specify it only wants to be notified of certain events, and not every event the subject might generate. For example, I might want a logging observer that records all activity to a log file, but also an error reporting observer that sends an email to an administrator when an error occurs, but only when an error occurs. You could write the error logger to ignore notifications that aren't triggered by an error (assuming that it is possible to modify this pattern so that specific kinds of notifications could be sent), but I suspect that this would be less efficient than ideal. I suspect that allowing observers to only subscribe to specific subject events would be better, but can that approach be implemented with SplObserver?

Was it helpful?

Solution

The splSubject does send itself when sending notifications. It's possible to implement a callback method in the subject so observers can figure out what exactly has changed.

function update(SplSubject $subject) {
   $changed = $subject->getChanges();
   ....
}

you would have to probably create a new interface to force the existence of getChanges() in the subject.

On different kind of notifications, you can take a look at message-queue systems. They allow you to subscribe to different message-boxes ('logging.error', 'logging.warning', or even 'logging'), where they will receive notifications if another system (the subject) sends a message to the corresponding queue. They're not much more difficult to implement as the splObserver/splSubject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top