March 31, 2012
In Object Oriented Programming which object should maintain the many to many relationship? (if there is one)
Question by Matt
I’ll use an example to illustrate this:
class Company {
}
class Person {
}
Company
and Person
hold a many to many relationship. A Person
can belong to multiple Companies
and a Company
can hold multiple People
.
Would I then need to create a third class:
class CompanyPerson {
}
or should the company handle it:
class Company {
function add_person() {
}
}
or maybe the Person
should?
class Person {
function add_to_company() {
}
}
Answer by Starx
This depends on the use case, but generally many to many object relationship can be deployed using a reference class
class CompanyPersonRelationship {
public $company;
public $person;
}
So now, both company and person can keeps track of their relationship lie
class Company {
public $persons = array();
}
class Person {
public $companies = array();
}