您給出的例子是多對多關聯,所以它最好使用3d對象來表示關聯。如果它的途中(一對多),那麼你提到的簡單組合就沒問題。
下面是示例代碼,可以在代碼中進行少許改進 1.實現工具&技術的getter setter,並使變量保持私有狀態。 2.使用接口而不是類直接爲工具&技術。 3.在配對類中使用2個不同的索引(數組)來提高獲取函數的性能,如果不考慮性能,那麼你可以使用一個數組。
<?php
class Technology{
public $id;
public $title;
public function __construct($id, $title){
$this->id = $id;
$this->title = $title;
}
}
class Tool{
public $id;
public $title;
public function __construct($id, $title){
$this->id = $id;
$this->title = $title;
}
}
class TechnologyToolPair{
private $techIndex = array();
private $toolIndex = array();
//Index by id, you can replace title if u maily search by title
public function addPair($tech, $tool){
$this->techIndex[$tech->id]['technology'] = $tech;
$this->techIndex[$tech->id]['tool'][] = $tool;
$this->toolIndex[$tool->id]['tool'] = $tool;
$this->toolIndex[$tool->id]['technology'][] = $tech;
}
public function getByTechnologyId($id){
return $this->techIndex[$id];
}
public function getByToolId($id){
return $this->toolIndex[$id];
}
public function getByTechnologyName($name){
foreach($this->techIndex as $index => $value){
if(!strcmp($name, $value['technology']->title)){
return $value;
}
}
}
}
$tech1 = new Technology(1, 'php');
$tech2 = new Technology(2, 'java');
$tool1 = new Tool(1, 'eclipse');
$tool2 = new Tool(2, 'apache');
$tool3 = new Tool(3, 'tomcat');
$pair = new TechnologyToolPair();
$pair->addPair($tech1, $tool1);
$pair->addPair($tech1, $tool2);
$pair->addPair($tech2, $tool1);
$pair->addPair($tech2, $tool3);
var_dump($pair->getByToolId(1));
var_dump($pair->getByTechnologyId(2));
var_dump($pair->getByTechnologyName('java'));
看到我下面的評論...我不知道這是否有所作爲。 – IOInterrupt 2012-07-20 15:16:29
@IOInterrupt:如果'Technology'不需要工具來工作,但只有幾種方法需要它們,則直接將其注入這些方法:'public function workWithTool(Tool $ tool,$ stuffToDo){' – 2012-07-20 15:19:21
我可能用過可能不好。這與我們現在的模型看起來有點類似。但是,假設我們有一個擁有技術的數據庫模型,每個模型都有多個與之關聯的工具。假設我們有另一個實體,比如Programming,它有許多與它關聯的Technology對象,並且技術將會有許多與之相關的工具。我們並不總是在意與該技術相關的工具,因此我們可能不會將它們包含在查詢中,因此不需要將工具與技術相關聯。 – IOInterrupt 2012-07-20 15:37:12