我对使用symfony3和学说的代码组织有疑问:我将尽力解释清楚。假设我有一个FootballClub实体:
class FootballClub
{
// other code
private $memberships;
public function addMembership(Membership $membership) : FootballClub
{
$this->memberships[] = $membership;
return $this;
}
public function removeMembership(Membership $membership) : bool
{
return $this->memberships->removeElement($membership);
}
}
该实体与另一个实体,即会员资格,具有多对一关系,代表球员与俱乐部之间的合同。假设每个俱乐部 具有只能获取的有限数量的成员资格,该数目表示为设置,例如表示为设置实体中的属性。 问题是:从俱乐部删除会员资格并检查是否受到尊重时,我应如何参考该设置?实体不应该有任何依赖关系,那么实现这一点的正确方法是什么?服务?你能提供一个例子吗?感谢您的时间。
答案 0 :(得分:0)
您可以创建一个Settings
实体,该实体与OneToOne
实体具有FootballCluc
关系。
定义这样的设置并在FootballClub
的构造函数中实例化它
设置实体
/** @Entity */
class Settings
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $maxMembership;
// Other configurable properties ...
__constructor($maxMembership = 50)
{
$this->maxMembership = $maxMembership;
}
public function getMaxMembership()
{
return $this->maxMembership;
}
public function setMaxMembership($maxMembership)
{
$this->maxMembership = $maxMembership;
}
}
足球实体
class FootballClub
{
/**
* One FootballClub has One Settings.
* @OneToOne(targetEntity="Settings")
* @JoinColumn(name="settings_id", referencedColumnName="id")
*/
private $settings;
// other code
private $memberships;
__constructor(Settings $settings = null)
{
if (null === $settings) {
$settings = new Settings();
}
$this->settings = $settings;
}
public function addMembership(Membership $membership) : FootballClub
{
if ($this->settings->getMaxMembership() <= count($this->memberships)) {
// throw new Exception("Max number of membership reached"); Strict mode
// return false // soft mode
}
$this->memberships-> = $membership;
return $this;
}
public function removeMembership(Membership $membership) : bool
{
return $this->memberships->removeElement($membership);
}
}