Skip to content

Instantly share code, notes, and snippets.

@technetium
Last active October 26, 2018 08:13
Show Gist options
  • Save technetium/cd35340834dbdd0111f12839316d08e7 to your computer and use it in GitHub Desktop.
Save technetium/cd35340834dbdd0111f12839316d08e7 to your computer and use it in GitHub Desktop.
Association Management Methods

Altough the Doctrine documentation about Working with associations states: "proper bidirectional association management in plain OOP is a non-trivial task and encapsulating all the details inside the classes can be challenging" I've used the following management methods (getters. setters, adders and removers) quite successfully.

<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity */
class Many
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Many", inversedBy="manys")
*/
private $one;
/**
* @return One|null
*/
public function getOne()
{
return $this->one;
}
/**
* @param One $one
* @return $this
*/
public function setOne(One $one = null)
{
if ($one != $this->one) {
if ($this->one) { $this->one->removeMany($this); }
$this->one = $one;
if ($one) { $this->one->addMany($this); }
}
return $this;
}
}
<?php
// Entitty/One.php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class One
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Many", mappedBy="one", cascade={"persist"})
* @var ArrayCollection
*/
private $manys;
/**
* One constructor.
*/
public function __construct()
{
$this->manys = new ArrayCollection();
}
/**
* @return ArrayCollection
*/
public function getManys(): ArrayCollection
{
return $this->manys;
}
/**
* @param ArrayCollection $manys
* @return $this
*/
public function setManys(ArrayCollection $manys)
{
$this->manys = $manys;
return $this;
}
/**
* @param Many $many
* @return $this
*/
public function addMany(Many $many)
{
if (!$this->manys->contains($many)) {
$this->manys->add($many);
$many->setOne($this);
}
return $this;
}
/**
* @param Many $many
* @return $this
*/
public function removeMany(Many $many)
{
$many->setOne(null);
$this->manys->removeElement($many);
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment