为已过时的对象集合选择数据结构

dna*_*irl 5 php spl date data-structures

我正在尝试设计一个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;
  }

}
?>
Run Code Online (Sandbox Code Playgroud)

起初我想我只是创建我的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*/
}
?>
Run Code Online (Sandbox Code Playgroud)

但是因为Incident对象具有自然顺序,我认为可能扩展其中一个SPL数据结构可能更合适/更有效.但是哪一个?我不清楚何时使用特定的数据结构.

另一个问题是,可能存在限制Incident_Collection.例如,如果有一个Person对象有一个Incident_Collection,可能会有以下限制:

  • 只有1 Birth件事
  • 如果Birth存在,它必须是集合中最早的事件
  • 只有1 Death件事
  • 如果Death存在,它必须是集合中的最后一个事件
  • HS_Graduation 必须来 HS_Begin

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

Gor*_*don 3

查看

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

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

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