views:

44

answers:

1

I want to use observer pattern for a logging system.

We have got logObservers and logObservables.

The class that will have to log something will implement iLogObservable and include these methods:

private $logObservers = array();

public function addLogObserver($logObserver) {
    $this->logObservers[] = $logObserver;
}
public function removeLogObserver($logObserver) {
    this->logObservers[] = $logObserver;
}
public function write($type, $message) {
    foreach($this->logObservers as $logObserver) {
        $logObserver->log($level, $message);
    }
}

Then I noticed, that a lot of classes that will use logging will have these methods and I have to copy paste. So isn't it better to have these methods in a class I call LogObservable or just Log and then use strategy (instantiate this class inside all classes that will have to log). When I change the methods in Log, all logObservables will be affected.

However, I have not seen anyone use observer pattern with strategy pattern yet, but it seems to be very efficient and remove the duplications.

What do you think?

+2  A: 

It's not unusual for an object that supports this functionality to INHERIT from an Observable class, which supports these methods, in languages that support multiple inheritance.

I have never come across a solution that uses aggregation to support this, which is what you are describing, but given PHP doesn't support multiple-inheritance, it sounds like a reasonable work-around to me.

Oddthinking
php doesn't support multiple inheritance. i can only extend one time. that was what u were referring to? but if i use "extend" it could no longer extend other classes, and the classes that will need log will often extend other classes. i guess i cant extend LogObservable just because a class want logging functions, then all classes will extend this one, and hence cannot extend others.
never_had_a_name
Fayer, right. In many other languages, (e.g. C++, Python and arguably Java) you can extend from several classes, which is perfect for this scenario. However, you can't in PHP, so going with aggregation instead (as you describe) is the second-best solution. I wouldn't describe it as the "Strategy Pattern" though, as there are not a bunch of alternatives that might be aggregated - just the one.
Oddthinking
i guess its the only way then :)
never_had_a_name