I am building an open source library that I can sum up to something like that:
class SuperThing {
public function doStuff($object) {
// ...
}
}
I want to offer the possibility to the user of the library to add custom behavior.
For example, he might want to insert some logging at specific points in the operation, or he might want to modify the object at a certain point.
I see 2 ways of doing it:
the template method pattern seems appropriate, but it will force me to add a lot of protected method (like
beforeDoingThingA()
,afterDoingThingA()
…), and it will force the user of the library to extend my class to add his behavior.using events:
SuperThing::doStuff()
raises events, the user can register to whichever he wants.
Using events seems simpler, clearer and more maintenable to me...
But it seems to me that events would be mainly about dispatching a message that something happened. No letting someone "hook" into the operation and modify some objects. Maybe I'm wrong about this.
So are events appropriate for this situation? If not, is there an alternative to the template method pattern?