我正在尝试设计一个 PHP 对象(称为它Incident_Collection
),它将包含其他对象的集合,每个对象都实现一个Incident
接口。
<?php
class Foo implements Incident {
protected $incident_date; //DateTime object
protected $prop1;
protected $prop2;
//etc
public function when(){ //required by Incident interface
return $this->incident_date;
}
}
?>
起初我想我只是制作我的Incident_Collection
实现IteratorAggregate
并将 Incident 对象存储在集合的数组属性中:
<?php
class Incident_Collection implements IteratorAggregate {
protected $collection=array();
public function getIterator(){
return new ArrayIterator($this->collection);
}
public function sort(){
//sort by $incident->when() values in $this->collection
}
/*also __get($var), __set($var,$value), add(Incident $object), remove(Incident $object) and other functions*/
}
?>
但是由于Incident
对象具有自然顺序,我认为扩展其中一个SPL 数据结构可能更合适/更有效。但是哪一个?我不太清楚何时使用特定的数据结构。
另一个问题是Incident_Collection
. 例如,如果有一个具有 的Person
对象,则Incident_Collection
可能会应用以下限制:
- 仅 1
Birth
起事件 - 如果
Birth
存在,它必须是集合中最早的事件 - 仅 1
Death
起事件 - 如果
Death
存在,它必须是集合中的最后一个事件 HS_Graduation
必须紧随其后HS_Begin
Incident_Collection
拥有一个接受其所有者(例如Person
)的一组限制的泛型或子类会更好Person_Incident_Collection
吗?