I'm developing my php software using Doctrine2. It is quite simple to use it but I have a little problem and I would know what is the best practice in that situation. Maybe you could help me ! You'll have all my gratitude :-D
Situation :
I have 2 entities (User and Contacts)
Problematic :
I woud like that when I persist a contact :
Possible solutions :
I have some idea how to process this logic but I would like to know the best practice in order to do a good code because this application will be an open source application.
Not clean ideas :
With this solution, I must launch the repository method always before to persist a contact all around the application. If I forgot to launch it, the database integrity should be compromised.
This method is not recommanded, the entity should never access directly the entity manager.
Can anyone tell me what is the best practice to do so ? Thank you very much !
PS : Sorry for my poor english !
The best thing you can do here (from a pure OOP perspective, without even the persistence logic) is to implement this logic in your entity's setters. After all, the logic isn't heavy considered that a User
won't have many contacts
, nor the operation will happen very often.
<?php
class User
{
protected $contacts;
// constructor, other fields, other methods
public function addContact(Contact $contact)
{
if ($this->contacts->contains($contact)) {
return;
}
if ($contact->isMainContact()) {
foreach ($this->contacts as $existingContact) {
$existingContact->setMainContact(false);
}
$this->contacts->add($contact);
$contact->setUser($this); // set the owning side of the relation too!
return;
}
$mainContact = true;
foreach ($this->contacts as $existingContact) {
if ($existingContact->isMainContact()) {
$mainContact = false;
break; // no need for further checks
}
}
$contact->setMainContact($mainContact);
$this->contacts->add($contact);
$contact->setUser($this); // set the owning side of the relation too!
}
}
On the other side, think about adding a field to your user instead:
<?php
class User
{
// keep reference here instead of the contact (cleaner)
protected $mainContact;
}