When should you make an interface/contract, and when not? [closed]

Interfaces are public “contracts” whenever you want to be able to swap the implementation or give someone the flexibility to use another implementation you should use interfaces.

Example:

You want to store something so you can load it later.
You could use something like

public function save(MySQL $db, array $data);

But this is not very flexible and it ties you code to a MySQL implementation.
If you want to be open for other implementations, because you are building an public library or framework or whatever, you should do something like this.

public function save(Persistance $storage, array $data)
{
    // dome some random stuff with you data
    ...
    $storage->save($data);
}

In this case Persistence is an interface and it could look something like this.

interface Persistance
{
    public function save(array $data);
}

And you local implementation could look like this.

class MySQL implements Persistance
{
    public function save(array $data)
    {
        $this->insert('my_table', $data);
    }
}

But somebody else could use your code with a complete different persistence layer, Redis or Postgres for example, just by implementing your interface and injecting their own Persistence implementation.

This is just a simple example, but Interfaces are mostly to understand as contracts between classes and leave the implementation open.

The opportunity to implement multiple interfaces is nice but has nothing to do with multiple inheritance. Interfaces only make sure a class has some clearly defined in- and outputs, but how things are done in the background is completely open.

If you really want get into ‘multiple inheritance’ you should have a look at Traits.

Interfaces are used in frameworks and the PHPFig is defining a lot of standard interfaces lately to make framework components more exchangeable.

For example the PSR-16 simple cache interface makes it possible to exchange the cache layer implementation between frameworks.

Or the PSR-7 Request Response interface enables frameworks to exchange standardized middleware implementations for login, CRF security or other stuff.

There is a PSR-11 Interface for dependency injection containers, if frameworks change their implementation from their own DI container to the interface we will be able to use those frameworks with different DI container implementations.

Leave a Comment