r/PHPhelp • u/nobrandheroes • Jun 03 '16
Alternative to many parent classes?
I'm getting an inspection notice about a class of mine having 3 or more parent classes. I am extending an extended controller in a framework, so there is a chain of 5 classes total, starting with an abstract class.
It seems fine to me, but I'm interested in thoughts on alternatives. The usual sources aren't superhelpful here.
1
u/gripejones Jun 03 '16 edited Jun 03 '16
The standard answer in this case is - it depends. I, personally, don't like having deep inheritance and in the cases where I need something like that - these days - I lean on traits. This isn't a drop-in fix, but it could lead to some needed refactoring.
A real world example - I have several models that all need to access a particular API. I could create a parent class that extends the frameworks parent class and add the API functions there, but what I did instead was create a trait that I could use to add the api functionality to all of those classes.
namespace Some\Models;
class SomeModel extends FrameworkModel
{
use CanConnectToSomeAPI;
...
}1
2
u/HauntedMidget Jun 03 '16
While I agree that in this particular situation traits are probably better than a deep inheritance chain, they're also often overused. I tend to use traits only for simple stuff that doesn't involve the business logic. For anything else I prefer DI - relying on language assisted copy & paste feels a bit wrong IMO.
2
u/[deleted] Jun 03 '16
What you're probably looking for is the idea of composition over inheritance. Basically, extract the logic that you have in these parent classes to separate objects and make them dependencies of the child class.