假设有三个类:
发起人{ id
[int], name
[string], sponsoredProjects
[array of Project objects]}
项目{ id
[int], name
[string], desc
[string], [赞助商sponsors
对象数组]}
School { id
[int], name
[string], [项目projectsDone
对象数组}
我被困在SponsorsponsoredProjects
和Projectsponsors
之间。
从理论上讲,如果我创建了一个项目,那么我也需要为其创建赞助商。如果我创建赞助商,那么我也需要为它创建项目。
因此,这将导致无穷无尽的Project with Sponsor in their in their with Project in them with Sponsors and etc. 我是对的吗?同样的问题也应该适用于学校,因为他们有一系列项目,其中有一系列赞助商,有一系列项目等等。
如果是这样,那么我应该如何避免这个缺陷?
我的目标是临时从返回的多个 SQL 结果中创建所有这些对象,然后我将其发送到 JavaScript 页面。
final class Sponsor{
private $_id;
private $_name;
private $_projects;
public function __construct($id, $name, Project $projects){
$this->setSponsor($id, $name, $projects);
}
public function getId(){
return $this->_id;
}
public function getName(){
return $this->_name;
}
public function getProjects(){
return $this->_projects;
}
private function setId($id){
$this->_id = $id;
}
private function setName($name){
$this->_name = $name;
}
private function setProject(Project $projects){
$this->_projects = array();
foreach($projects as $val){
array_push($this->_projects, $val);
}
}
private function setSponsor($id, $name, Project $projects){
$this->setId($id);
$this->setName($name);
$this->setProjects($projects);
}
}
final class Project{
private $_id;
private $_name;
private $_desc;
private $_sponsors;
public function __construct($id, $name, $desc, Sponsor $sponsors){
$this->setProject($id, $name, $desc, $sponsors);
}
private function setId($id){
$this->_id = $id;
}
private function setName($name){
$this->_name = $name;
}
private function setDesc($desc){
$this->_desc = $desc;
}
private function setSponsors(Sponsor $sponsors){
$this->_sponsors = array();
foreach($sponsors as $obj){
$id = $obj->getId();
$name = $obj->getName();
$projects = $obj->getProjects();
array_push($this->_sponsors, new Sponsor($id, $name, Project $this));
}
}
private function setProject($id, $name, $desc, Sponsor $sponsors){
$this->setId($id);
$this->setName($name);
$this->setDesc($desc);
$this->setSponsors($sponsors);
}
}
final class School{
private $_id;
private $_name;
private $_projectsDone;
public function __construct($id, $name, Project $projects){
$this->setSchool($id, $name, $projects);
}
private function setId($id){
$this->_id = $id;
}
private function setName($name){
$this->_name = $name;
}
private function setProjectsDone($projects){
$this->_projectsDone = array();
foreach($projectsDone as $val){
$this->{_projectsDone}[] = $val;
}
}
public function setSchool($id, $name, $projectsDone){
$this->setId($id);
$this->setName($name);
$this->setProjectsDone($projectsDone);
}
}