I’m working on an old project where we have an entity that had a may to many collection via a join table :
class Company
{
private Collection $contacts;
public function getContacts(): Collection
{
return $this->contacts;
}
public function setContacts(Collection $contacts):void
{
$this->contacts = $contacts;
}
}
However, over time, the join table has become an entity of its own, so now as well as a Contact entity, we now have a CompanyContact entity. I’m refactoring the class to incorporate this change, but I’m not sure about the setContacts method. Here’s what I have now:
class Company
{
private Collection $companyContacts;
public function getCompanyContacts(): Collection
{
return $this->companyContacts;
}
public function setCompanyContacts(Collection $companyContacts):void
{
$this->companyContacts = $companyContacts;
}
public function getContacts(): Collection
{
return $this->companyContacts->map(function (CompanyContact $compayContact) {
return $companyContact->getContact();
});
}
// How should I write this method ???
public function setContacts(Collection $contacts):void
{
$this->contacts = $contacts;
}
}
I’m not sure how to set this. Should I be checking through the existing $companyContacts and adding/removing where necessary, or creating a new Collection? We want to preserve the old methods somehow.
The first method seems to be more correct than ditching the old collection and creating a new one, since that would mean losing the additional CompanyContact column data, so I’m a little bit stumped here, can anyone assist? Many thanks!