PHP Interfaces: How are they usable in practice?
I'll start by saying that I know how PHP interfaces work and how to "use" them.
My question is rather; how do they become 开发者_JS百科useful in real life applications?
I've been writing PHP for over 3 years now and have never felt the need for an interface. I am writing interfaces more for good practice than for a particular purpose.
I'll provide an example where I've used interfaces in my own real-world experience.
Interfaces are extremely useful when you need to define something like a plugin architecture. Suppose your application accepts authentication plugins, allowing your end user implementers to integrate with their own internal auth infrastructures (LDAP, Shibboleth, some custom auth database, whatever). In order for a plugin to be compatible, it must implement the following methods:
validate_user()
start_user_session()
logout_user()
get_user_details()
If defined in an interface, a class then implements the interface ensuring that the necessary methods are present for compatibility with the plugin architecture.
Unfortunately, PHP does not enforce the return type of interface methods, so you must simply take care to document the expected return functionality of your methods.
They are not so useful - yet. Their main purpose seems to be for type hinting. When you write two separate classes that implement the same interface, you can use that interface in the type hint for a function. That way, you know you got all the methods of that interface available in the object that is passed in the parameter.
Unfortunately, PHP doesn't actually check if any called methods or properties you call on that parameter are actually in that interface, so you can accidentally use an object property that is not available in the interface, causing potential bugs when an object of a different type is passed.
Other languages are much stricter in this situation and will only allow you to use only that functionality that is declared in the interface.
Nevertheless, they are convenient for this purpose in PHP too, and maybe these checks will become stricter in future versions, so it becomes less error prone.
Check out the Standard PHP Library (SPL) http://php.net/manual/en/book.spl.php
Countable and RecursiveIterator might give you a clue.
精彩评论