phpdatabase-abstraction

I'm finding I need to recreate class attributes in multiple un-related classes. Is my methodology wrong?


Let's say I have 3 classes:

User

Building

Car

Each of these has their relevant properties. E.g.

User has name, age, email
Building has age, rooms, fire_alarm
Car has brand, seats, top_speed

Let's say I have a database that stores the relationship between a user and a building and a user and a car.

In my Building class, my save_building method requires the user_id.

I have two choices here.

1) I can either re-create the user_id property in the Building class (redundant and fragile and would need to be duplicated in the Car class too) or
2) I could just reference the user object directly and get the user_id.

Neither of these seem 'right'.

When I set my attributes, I validate them too and then store any errors of those validations in the object itself. If I use option 2, I would have to check the other object for errors before allowing my save_building method to proceed rather than only having to check the object I'm working with.

Is option 1 the correct way forward or is option 2?

Edit: For clarity, the database relationship tables are as follows:

user_buildings: user_id, building_id
user_cars: user_id, car_id

Edit2: Making the question non-open ended.


Solution

  • The relationship between users and buildings had to be stored in the database, so clearly is needs to manifest in your classes somehow. There is nothing redundant about storing object references for the purpose of establishing the relationships of objects, so don't think that it is. The only redundancy that could potentially be removed is having users and buildings pointing to each other versus only having one point to the other. This is sort of like the question of whether one should use a singly-linked list versus a doubly-linked list.

    Given your two options, I would prefer option 1, because in the case of User being unknown, you can set it to null which is more semantic than 0 or -1 or whatever integer equivalent in the case where the user was not queried/joined in the database or no relationships exist yet.

    Another option which you didn't list is to have save_building ignorant of relationship changes between users and buildings. Maybe this functionality should only be handled in the user class. Maybe you want a new class building-owner class whose purpose is to handle this functionality.