I\'m curious if there is a \"better\" design for the following behavior:
As long as you're overwriting your methods in subclasses, there is no way in any language I know of to enforce the behavior of the parent's method. If you're writing code just for your app, you should be able to trust your own code to call parent::foo(). But if you're writing a library, framework or API that others will build on, there is value to your idea. Ruby on Rails makes good use of that kind of behavior using callbacks.
Okay, so don't define any foo methods. Instead, use __call and an array of closures as callbacks. My PHP is really rusty, so I forget some of the specifics.
class Foo {
// I forget how to make a class variable in PHP, but this should be one.
// You could define as many callback chains as you like.
$callbacks = array('foo_callback_chain' => []);
// This should be a class function. Again, forget how.
function add_callback($name, $callback) {
$callbacks[$name.'_callback_chain'][] = $callback;
}
// Add your first callback
add_callback('foo', function() {
// do foo stuff
})
def method__call($method, $args) {
// Actually, you might want to call them in reverse order, as that would be more similar
foreach ( $callbacks[$method_name.'_callback_chain'] as $method ) {
$method();
}
}
}
Then in your child classes, just append more callbacks with ""add_callback". This isn't appropriate for everything, but it works very well in some cases. (More about closures at http://php.net/manual/en/functions.anonymous.php.)