您给出的示例是多对多关联,因此最好使用 3d 对象来表示关联。如果它在路上(一对多),那么你提到的简单组合就可以了。
下面是示例代码,可以在代码 1 中进行一些改进。为工具和技术实现 getter setter 并将变量设为私有。2. 直接为工具和技术使用接口而不是类。3.在pair类中使用2个不同的索引(数组)来提高get函数的性能,如果不关心性能,那么你可以只使用一个数组。
<?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'));