/
Collection.php
120 lines (87 loc) · 2.25 KB
/
Collection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?PHP
// This represents a collection of objects of any kind
class Plank_Collection implements Iterator {
private $collection = array();
private $type = 'Objects';
private $sort = '';
private $position = 0;
function __construct($array = false){
$this->position = 0;
if($array){
$this->collection = $array;
} else {
$this->collection = array();
}
}
function __toString(){
return "A collection of ".count($this->collection)." ".$this->type." things";
}
function setType($type){
$this->type = $type;
}
static function getLastTen($type, $field){
$obj = new $type();
$collection = new Plank_Collection($obj->_collection_list($field, 10 ) );
$collection->setType($type);
return $collection;
}
static function find($type, $field, $value, $op = '=', $sort = null, $limit= null){
$obj = new $type();
$array = $obj->_collection_find($field, $value, $op, $sort, $limit );
$collection = array();
foreach($array as $element){
$collection[] = new $type($element);
}
$collection = new Plank_Collection($collection);
$collection->setType($type);
return $collection;
}
function asArray(){
return $this->collection;
}
function sortBy($thing){
$this->sort = $thing;
usort($this->collection, array($this, 'compare'));
}
function compare($a, $b){
if ($a->get($this->sort) < $b->get($this->sort)){
return 1;
} elseif ($a->get($this->sort) > $b->get($this->sort)){
return -1;
}
return 0;
}
function count(){
return count($this->collection);
}
// Iterators:
function rewind() {
#var_dump(__METHOD__);
$this->position = 0;
}
function current() {
#var_dump(__METHOD__);
return $this->collection[$this->position];
}
function key() {
# var_dump(__METHOD__);
return $this->position;
}
function next() {
#var_dump(__METHOD__);
++$this->position;
}
function valid() {
# var_dump(__METHOD__);
return isset($this->collection[$this->position]);
}
function add($that){
$this->collection[] = $that;
}
function remove($id){
unset($this->collection[$id]);
}
function getid($id){
return $this->collection[$id];
}
}