5

我正在尝试设计一个 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可能会应用以下限制:

  • 仅 1Birth起事件
  • 如果Birth存在,它必须是集合中最早的事件
  • 仅 1Death起事件
  • 如果Death存在,它必须是集合中的最后一个事件
  • HS_Graduation必须紧随其后HS_Begin

Incident_Collection拥有一个接受其所有者(例如Person)的一组限制的泛型或子类会更好Person_Incident_Collection吗?

4

1 回答 1

3

查看

它很好地概述了 SPL 数据结构、它们是什么以及何时使用它们。还有基准。

如果这是一个对象集合,我肯定会考虑使用 SplObjectStorage 而不是普通的数组。如果事件应该是 LIFO 或 FIFO 顺序,请考虑队列和堆栈。如果您需要按自定义顺序使用它们,请考虑使用Priority Queue

关于限制,您可以使用状态模式,例如通过一般 IncidentCollection 进行访问,但根据其所有者属性,应用子类来处理状态更改。但是,这要求集合具有所有者属性。因为各个状态无论如何都是 IncidentCollection 的子类,所以您也可以直接使用它们。

于 2011-01-27T23:07:25.930 回答