I have a data mapper class…
I’m confused whether to use
abstract class Mapper extends DatabaseHandler
or
public function __construct(DatabaseHandlerInterface $dbh) {
$this->dbh = $dbh;
}
I see that using composite is more flexible since it can be based on the interface.
So, which one do you prefer ?
When to use inheritance over composite ?
And, I also want to ask the difference between composite and dependency injection ? Are they synonymous ?
I think this video explains the difference fairly well.
So, the comparison between inheritance and composition boils down to is-relationships (inheritance) as opposed to has-relationships (composition).
Since the Mapper has a relationship to the database and isn’t a direct relationship to the database from an application point of view, I believe it would be better to use composition.
I am also learning OOP (properly), so I might be wrong too.
There are very few relationships which can’t be expressed as has-a. Is an employee a person? I’d argue an employee is a person that has a job. Is a cat a mammal or an animal with warm blood and mammary glands?
Generally speaking, doing this inversion makes your code easier to test, more flexible and easier to reuse.
Pretty much. The main problem with inheritance is that is always tightly coupled. class Employee extends Person tightly couples the person and employee classes, whereas new Person(new Job)) loosely couples the person and job classes.
I think, if I could actually completely understand these “Rules of Thumb” about OOP structural patterns or these about creational design patterns, then I can consider myself pretty good at OOP. Right now, some of it seems pretty alien to me. LOL!