I’m expanding my php and general coding knowledge by writing my own ‘simple’ CMS system.
My database structure follows:
USERS --< WEBSITES --< PAGES
In my logic, I have three classes, a User, Website and Page class. NOT INHERITED
The User class has all the attributes from the USER TABLE plus a $_website attribute,
The Website class has all the attributes of the WEBSITE TABLE plus an ARRAY of Page objects
The way I have decided to work this is, on page load, these classes will be created and filled with the database data.
So then in the html I can echo out results simply by calling the class like so:
$USER -> name;
$USER -> website -> get_pages();
$USER -> website -> pages[0] -> get_header();
I Realised that these classes could be inherited, so Page inherits Website and Website inherits User
But if I do it that way, then I’ll instantiate the Page class like:
$PAGES = array();
$PAGES[] = new Page( $constructor_data_to_construct_user_website_and_page );
Now IF I do it this way, the object $PAGES[0] will have all the info to do with that page, and all the info to do with the Website (first parent),
and all the info to do with the User ( second parent )
If i then create another Page, i’m just copying the same User and Website details Yes?
So if i were to var_dump $PAGES[0] id get ALL the info to do with USER, WEBSITE and PAGE
If i were to var_dump $PAGES[1] id get ALL THE SAME information for USERS AND WEBSITE, but just the different Page data.
So inheritance, is causing unnecessary copying of the User and Website objects
Because I could essentially do:
$PAGES[0] -> username // username is a property of the Users class
$PAGES[1] -> username
both would return EXACTLY the same value.
surely this is bad because data is being unnecessarily copied!
Is This Correct?
Or is this question a load of rubbish and this isn’t the kind of situation inheritance is used?
This is exactly the sort of situation where you must not use inheritance.
Inheritance is meant to model an
IS-Arelationship. Typical example: aStudentis a type ofPerson, soStudentinherits fromPerson.Inheritance is not, not, NOT meant to model a
HAS-Arelationship. Typical example: aCarhas anEngine, butCaris not a type ofEngine.When we have a
HAS-Arelationship (e.g. a User has Website) you should almost in all cases use composition instead of inheritance:Bad
Good