-->

When to use Interfaces in PHP

2020-08-20 07:06发布

问题:

I have always had a hard time understanding the real value of Interfaces when coding with Objects in PHP (could be other languages I imagine)

From what I understand you use an Interface to enforce or guarantee that when a Class is using an Interface that that class will have the methods defined in the Interface inside of that class.

So from my litte knowledge of using them, wouldn't that mean you would only find an Interface beneficial when defining more then 1 class that needs those Methods?

To be more clear, if I have a class that does one thing and no other classes need to do that kind of thing, then it would be pointless to use an Interface on that class?

So you wouldn't use an Interface on EVERY class you right?

PS) If you vote this question as exact duplicate then you didn't read the question and only the title as I have read most of the similar questions already

回答1:

From what I understand you use an Interface to enforce or guarantee that when a Class is using an Interface that that class will have the methods defined in the Interface inside of that class.

This is actually only half of the deal (the technical part). There's also the all-important architectural half, which appears when you consume the interface and it goes like this:

function feed(IAnimal $interface) {
    // ...
}

(alternatively, a "factory" function that is documented to return an instance that implements IAnimal would also serve as an example).

The idea here is that the consumer of the interface says: "I want an animal to feed. I don't care if it flies, walks, or crawls. I don't care if it's big or small. I only care that it shares some features with all other animals" -- features that would comprise the definition of the interface.

In other words, interfaces serve to abstract the contract (interface) from the concrete implementation (classes). This gives implementers of concrete classes a free hand to modify, rename, remove and add implementations without breaking the code for users of the interface, something that is not possible if you are referencing concrete classes directly in your API.

As for the interface that is implemented by one class only: that's not enough information to decide. If there can plausibly be more implementations of the interface in the future, then it certainly does make sense (for example: an IHashFunction interface would make sense even if Sha1HashFunction were currently the only available implementation). Otherwise it doesn't offer anything.