PHP Interfaces – Should You Extend an Interface or Keep It Independent?

inheritanceinterfacesPHP

I'm trying to decide whether to extend a base interface with additional methods or create several independent interfaces. I have a Task interface that looks like this

interface Task
{
    public function name();
    public function run(array $args);
}

Now I want to add optional description and dependencies methods. Should I create a new DetailedTask interface like this?

interface DetailedTask extends Task
{
    public function description();
    public function dependencies();
}

This way I could choose to implement either the base Task interface for a basic task class, or the DetailedTask interface if I needed a description and dependencies. Alternately I could create separate interfaces for the extra methods like this.

interface Describable
{
    public function description();
}

interface TaskDependent
{
    public function dependencies();
}

According to the interface segregation principle, the second is better because it is more flexible. However, I don't ever anticipate using Describable and TaskDependent on anything besides a Task instance. The extra interfaces just seem to add extra complexity. Which technique should I use?

Best Answer

First of all, with your question details:

Now I want to add optional description and dependencies methods.

If you want an optional method, then you should not go for interface, because as per interface rules, you MUST need to define methods in implementation class. See PHP interface.

So according to that rule, your first solution will not work because if you define class that implements DetailedTask, then that class must define both method description and dependencies.

The second way will give you freedom to choose whatever interface you want to implement.

Related Topic