【发布时间】:2011-01-27 22:39:46
【问题描述】:
我正在尝试设计一个 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 Data Structures 之一可能更合适/更有效。 但是哪个?我不太清楚何时使用特定的数据结构。
另一个问题是Incident_Collection 可能存在限制。例如,如果有一个 Person 对象拥有一个 Incident_Collection,那么可能会应用以下限制:
- 只有 1 个
Birth事件 - 如果
Birth存在,则一定是集合中最早的事件 - 只有 1 个
Death事件 - 如果存在
Death,则它必须是集合中的最后一个事件 -
HS_Graduation必须在HS_Begin之后
最好有一个通用的Incident_Collection 接受其所有者的一组限制(例如Person),还是一个子类Person_Incident_Collection?
【问题讨论】:
标签: php data-structures date spl