Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 488
thwd Avatar asked Sep 11 '11 19:09

thwd


1 Answers

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.

like image 143
Michael Berkowski Avatar answered Sep 29 '22 04:09

Michael Berkowski