I don’t know what’s the best practice for this.
Let’s say I have some hierarchical objects:
Neighborhood
Family
So each Family lives in a Neighborhood.
The objects are mapped like this:
class Neighborhood {
public $id;
public $name;
public $nr_families;
}
class Family {
public $id;
public $name;
public $neighborhood_id;
}
Each Object models it’s own database table. All objects of a type are kept in an array in the global scape, so there are 2 arrays.
How can I know, FROM INSIDE the Neighborhood object, at the CREATION DATE, how many Families are in that Neighborhood, without quering the database again or accessing the global array of Families? Let’s say the Family array was generated first, they are already there, and now when I generate the Neighborhood array, these objects need to have a property with the total number of families in each. This property doesn’t match a database field, it has to be calculated on the fly.
Is there a design pattern? Should I use some kind of third object?
If you don’t want to use extra queries, you need to loop over the list of families to check the family’s neighborhood id. Because using global variables is discouraged, you can use some dependency injection to tell the neighborhood about the families.
Say your Neighborhood object has a static variable that contains the list of families. Outside your object, you set that variable:
Neighborhood can now loop over that list, checking the family’s neighborhood id:
Would that work?