mardi 5 juillet 2016

How to inject an interface into a concrete class hierarchy

So, I have an existing class hierarchy that I can't modify. There are existing consumers of classes in that hierarchy in more than just my codebase. I have another class (in a new, but external library) that has a different contract (class prototype) with similar but improved functionality. I wish to provide that new functionality to existing consumers of the old code.

class OldBase {}

class OldSubClass extends OldBase{}

class NewCode {}

//consumers
existingMethod(OldSubClass $c) {}
alsoExistingMethod(OldBase $c) {}

I thought of using an AdapterInterface, but this seems, perhaps, inelegant.

interface NewCodeAdapterInterface
{
     //interface that mimics the contract from OldBase
}
class NewCodeImplementation implements NewCodeAdapterInterface{}

//now this code can not be used with any existing OldBase objects :-\
existingMethod(NewCodeAdapterInterface $c) {}

I'd like to ensure a backwards compatible way to allow old code to be used while allowing a clean way to use the new with as few ramifications as possible, but how?

Aucun commentaire:

Enregistrer un commentaire