Shuffling methods

I’m writing some quite complicated class structure in PHP, and I have realised there’s one feature I am missing in PHP – I need to be able to define an interface with default method implementation. Why not class? But of course because I can not inherit two classes. And I don’t really want multiple inheritance with all its problems – I want something much more restricted. Let’s see an example.

Let’s say I am definining interface “Kickable” having method kickMe, which describes an object that can be kicked. Most of the kickable classes would have this wonderful code:

function kickMe() {
    echo "Oy-vey!";

So if I have 20 classes which are kickable, I’d probably have to write this 18 times (2 classes would say something different when kicked). This is boring. I’d want somehow to say “OK, here’s a function, here’s the default, if you want – reimplement it”. If you ask what happens when I define two interfaces with defaults for kickMe – well, then either it would be an error or the latest implemented would win. It is not worse than having to implement two interfaces with same function names and different semantics anyway, and that is supported right now.

Alternatively, another approach would work – if I could “steal” a method implementation from a brother class (or, more nicely, delegate my function to it). I.e., suppose I have the 18 classes mentioned above, and I define the function once and in other classes I say something like:

function kickMe same as DefaultKicker::kickMe;

That would be fun – I can write much less code and additionally if I’d want to internationalize it so it could say “Oh my!” and “O-la-la!” – I could do it just once.

There are ways to do it now – I can shuffle functions with runkit, but that’s runtime – not nice (and runkit is not in default PHP anyway). I could also implement the default behaviour separately and call it on need – which would solve the consistency problem, but would solve the boredom problem only partially and would not solve the problem that external implementation couldn’t access protected class data.

I could probably use some design pattern to do it, but I didn’t find anything that does exactly that (decorator looks similar, but it assembles at runtime, and I need design-time).