I was just refactoring some functionality in my code base, moving away from 3 parallel sets of functions toward 3 class definitions which now expose the former functions as class methods. Some of the methods should be private. Some of the methods would have been completely identical across the 3 classes so what I've done is define those methods in a trait. Each of the 3 classes uses the trait. Because the 3 sets of functions mirrored one another, each with their own implementation, I've defined an interface which all 3 classes implement. I like that interfaces force the implementing class to expose all public methods defined in the interface. Methods in the trait call private methods in the classes, each of course having the same name so that the trait code does not break regardless of which class is using. The next goal I had was to enforce each class defining the private methods depended upon by the trait. I could of course manage this manually, but in team programming, for example, does it not now make sense with php's introduction of traits, that we have the ability to define the private methods a class must represent? My work-around to enforce the existence of would-be private methods in my 3 classes was to define them as abstract protected methods in an abstract class. My 3 classes extend that abstract class and of course define their own versions of the protected methods. Php does not allow one to define abstract private methods. Interfaces can only define public methods. I'm seeing a hole--I believe there is now a need, thanks to traits, to be able to define private methods that must be "exposed" by the class. I have achieved no code duplication and what I think is some highly maintainable code. But with traits, is php now missing something without a way to enforce the existence of private methods in classes?
|