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();
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!