Object-oriented – Which methods should be put in an interface and which in abstract classes

abstract classcodinginterfacesobject-orientedPHP

I have seen many frameworks and modules and their standard they follow is like this

  1. UserInterface which have some predefined methods
  2. AbstractUserClass which implements userInterface
  3. Then GenericUserClass which extends from AbstractuserClass
  4. Then other classes extending from that generic

Now I have seen that abstract class has additional functions to the interface, and the generic class also has additional functions.

  1. So I am confused which methods should go where
  2. Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements UseraInterface. What is the difference if Abstractclass already impelements Userinterface

Best Answer

A rule of thumb is that:

  • Interfaces define the public API (contract) or a certain functionality if you will,
  • Abstract classes (may) provide a private API (for extended classes to use), such as shared functionality.

So i am confused which methods should go where

If a method should be part of the public API, add it to the interface and update dependencies where necessary (i.e. Abstract and / or Generic class).

Otherwise, implement the method as high up as is needed based on how generic or specific it is.

Sometimes i see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements useraInterface. what is the difference if Abstractclass already implements Userinterface

There's no difference in that case; you don't have to specify an interface twice if the ancestor already implements it, because the interpreter will throw an error if you try to break the contract.

This would only make sense if the child class implements another interface altogether. And this is a strength of interfaces; since you're defining a piece of functionality rather than a specific implementation, you can make any class implement any interface if you wanted to. This is a great help when writing mock classes for testing.