gpt4 book ai didi

php - 为数据对象集合选择数据结构

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:42:48 24 4
gpt4 key购买 nike

我正在尝试设计一个 PHP 对象(将其称为 Incident_Collection),该对象将包含其他对象的集合,每个对象都实现了一个 Incident 接口(interface)。

<?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 并将事件对象存储在集合的数组属性中:

<?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 可能存在限制。例如,如果有一个具有 Incident_CollectionPerson 对象,则可能会应用以下限制:

  • 只有 1 个出生事件
  • 如果 Birth 存在,则它必须是集合中最早的事件
  • 只有 1 起死亡事件
  • 如果 Death 存在,它必须是集合中的最后一个事件
  • HS_Graduation 必须在 HS_Begin 之后

有一个通用的 Incident_Collection 接受来自其所有者(例如 Person)的一组限制,还是一个子类 Person_Incident_Collection 会更好>?

最佳答案

checkout

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

如果这是一个对象集合,我肯定会考虑使用 SplObjectStorage 而不是普通数组。如果事件应采用 LIFO 或 FIFO 顺序,请考虑队列和堆栈。如果您需要定制订单,请考虑 Priority Queue .

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

关于php - 为数据对象集合选择数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4822777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com