PHP Interfaces — Why Use Them?

In PHP, an interface is nothing more than the ‘skeleton’ of a class.  You can’t put any non-public code into it, you can’t add properties, or otherwise add functionality.  It doesn’t in any way help with the normal approach to abstraction, wherein lower level classes handle details so the higher level ones can focus on other things.  In many ways, it seems an absolutely pointless idea.

In and of itself, you could make that argument.  Interfaces don’t ‘do’ anything on their own other than add restrictions to your code.  If you implement an interface, you’re required to add all the required methods — even if you don’t think some of them are needed or make any sense.

The real ‘power’ of an interface isn’t in helping to re-use code, it’s in the fact that it’s a ‘contract’ that your classes are obliged to fulfill.  Yes, it requires more work, but it’s work that’s designed to help the programmers.  As my immediately previous post about Objective-C points out, with more powerful compilers and computers, we have the option of backing away from having to work and think like a machine would.  Instead, we can focus on things that machines can’t do — like create logic that is suitable to a task.  Interfaces are a language level tool to help us do that.  They provide the framework that tells us we need to complete a given set of methods, which allows auto complete to fill in calls to those methods even before we finish writing them.  They actually improve code-reuse by allowing us to focus on a specific set of code, while leaving other details to the implimentor.  A plugin can simply say ‘give me a class that fulfills this interface’ and proceed on using it, not knowing or caring how you fulfill your responsibilities — be they saving data (to a disk, a database, or remote server), or actually sending the text message you just created.

In a sense, Interfaces allow you to invert the normal inheritance approach towards abstraction, defining lower level tasks without worrying about big picture items.  Your interface lets you say ‘OK, I’ve done this work for you.  Now, I need you to save this file to disk to retrieve later’.

In some cases, this could be done through the use of abstract classes.  That’s also a very valid approach.  But the use of abstract classes enforced a hierarchical decision, whereas interfaces allow for ‘sibling’ classes that don’t interact at all, except via the interface.  It’s a tool, no more and no less.  Use it as appropriate, don’t use it when another tool fits better.

One thought on “PHP Interfaces — Why Use Them?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>