One of the big pillars of "Design by Contract" (http://en.wikipedia.org/wiki/Design_by_contract), interfaces are powerful structures that permit you to develop well-organized, object-oriented applications, even in weakly-typed languages such as PHP. If you’ve used interfaces in the construction of your own PHP programs, then you should be aware of the many benefits they bring to the table: coding to an interface and not an implementation, favoring Composition over Inheritance (a crucial facet of Dependency Injection), type-hinting arguments in class methods and so forth.
Editor's Note: This article has been published out of sequence. You can find the second and third parts of this series at:
Unfortunately, due to the fact that we’re imperfect and sometimes “unconscious” creatures, we tend to abuse interfaces and misuse them. Not that I’m claiming that you’re guilty of this (in my case, mea culpa), but eventually the contracts that we define for our classes can be too generous. But what does this mean in simple terms?
Well, consider the following example: say that you’re building a custom array iterator, which will be capable of traversing arrays by using a “foreach” construct. To add the functionality required by this class, you define an interface called “Collection”, which extends the native classes “Countable”, “Iterator” and “ArrayAccess”. Finally, you make the iterator an implementer of the shiny “Collection” interface.
Now, think about this situation a bit more carefully: if your iterator will be aimed only at traversing arrays, why are you giving it the ability (in this case unnecessary) to count and access elements? In fact, what you’re doing defining a contract for the iterator that gives it more functionality than the one that it really needs to get its job done.
The good news is that this issue can be easily solved by means of segregated interfaces. Don’t worry about their fancy names, because you’ve probably used them before without knowing what they were called. Back to the earlier example - if you modify your array iterator and make it only implement the “Iterator” PHP interface, you’re already utilizing a segregated interface. This implies that a segregated interface is nothing but an ordinary interface, whose contract suits (exactly) the needs of one or multiple classes, be they related to each other or not.
Of course, the best manner to demonstrate the functionality of segregated interfaces is by example. In this article series I’ll be developing some segregated interfaces in the construction of some practical projects, which you’ll be able to tweak at will.