Developer Blog

  • Blog
  • /
  • Naming Interfaces in PHP
By Dracony on 28 October 2014

I am frequently relying interfaces in PHPixie components and have faced the problem of how should I be naming them. Specifically whether the “Interface” suffix should be added to the name.

Most frameworks in PHP have decided to adopt the suffix approach, there are some notable exceptions though, like for example Zend 2. Usually when facing an OOP-related question I try to see how it’s done in Java and C++, and the consensus there seems to be quite different. Let me try to explain why:

In the OOP world both classes and interfaces are considered types. When using strict typing declaring a variable of both types is the same. So from the perspective of the developer that is using your library there is no difference between whether the type he is relying on is a class or an interface. This is one of the cool things that actually made interfaces that useful.

Skipping the suffix also allows you to easily refactor your existing concrete dependencies to interfaces.

1
2
3
4
5
6
7
8
9
abstract class Spell
{
/**/
}

class Fairy
{
    public function cast(Spell $spell);
}

The Fairy class is relying on a concrete Spell implementation right now, but it’s much better to depend on an abstraction so let’s change it to an interface:

1
2
3
4
5
6
7
8
9
10
interface Spell
{
/**/
}

//The classes relying on the Spell type don't have to change
class Fairy
{
    public function cast(Spell $spell);
}

Changing the Spell type into an interface could be done in one place. You don’t need to change the classes depending on it. This saves you and people that are already using your library time, since it doesn’t cause backwards compatibility breaks. If you change the name too you now get:

1
2
3
4
5
6
7
8
9
10
interface SpellInterface
{
/**/
}

//People using your library now have to change their code
class Fairy
{
    public function cast(SpellInterface $spell);
}

If you follow the suffix approach the only way to assure that your code will be backwards compatible is to have interfaces for everything from the start, which is of course the best approach.

if you follow best practices and all you dependencies are already interfaces there is no point in adding the suffix to them, since you already know that you never depend on concretions

Also, prefixes and suffixes in type names don’t carry any domain significance. A Spell type represents a spell domain entity. The words “Interface” and “Abstract” don’t really belong in the domain field, they are part of the type definition, but not the type itself.

the bottomline is: if you want shorter names, easier refactoring and semantic meaning you should name your types what they represent and not what they are.

comments powered by Disqus