forked from Djuki/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIterator.php
119 lines (102 loc) · 2.63 KB
/
Iterator.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
<?php
namespace DesignPatterns;
/**
* iterator pattern
*
* Purpose:
* to make an object iterable
*
* Examples:
* - to process a file line by line by just running over all lines (which have an object representation) for a file
* (which of course is an object, too)
*
* Note:
* Standard PHP Library (SPL) defines an interface Iterator which is best suited for this!
* Often you would want to implement the Countable interface too, to allow count($object) on your iterable object
*
* THIS EXAMPLE ALSO APPLIES THE COMPOSITE PATTERN
*
*/
class File
{
protected $_rowset;
protected $_pathName;
public function __construct($pathName)
{
$this->_rowset = new Rowset($this);
}
public function process()
{
// this is the place to show how using an iterator, with foreach
// See the CardGame.php file
$this->_rowset->process();
}
}
class Rowset implements \Iterator
{
protected $_currentRow;
protected $_file;
public function __construct($file)
{
$this->_file = $file;
}
/**
* composite pattern: run through all rows and process them
*
* @return void
*/
public function process()
{
// this actually calls rewind(), { next(), valid(), key() and current() :}
/**
* THE key feature of the Iterator Pattern is to provide a *public contract*
* to iterate on a collection without knowing how items are handled inside
* the collection. It is not just an easy way to use "foreach"
*
* One cannot see the point of iterator pattern if you iterate on $this.
* This example is unclear and mixed with some Composite pattern ideas.
*/
foreach ($this as $line => $row) {
$row->process();
}
}
public function rewind()
{
// seek to first line from $this->_file
}
public function next()
{
// read the next line from $this->_file
if (!$eof) {
$data = ''; // get the line
$this->_currentRow = new Row($data);
} else {
$this->_currentRow = null;
}
}
public function current()
{
return $this->_currentRow;
}
public function valid()
{
return null !== $this->_currentRow;
}
public function key()
{
// you would want to increment this in next() or whatsoever
return $this->_lineNumber;
}
}
class Row
{
protected $_data;
public function __construct($data)
{
$this->_data = $data;
}
public function process()
{
// do some fancy things here ...
}
}