101 lines
1.9 KiB
PHP
Raw Normal View History

<?php
2013-09-21 22:17:54 +02:00
namespace DesignPatterns\Iterator;
/**
2013-09-21 22:17:54 +02:00
* Class RowSet
*/
2013-09-21 22:17:54 +02:00
class RowSet implements \Iterator
{
2013-09-12 11:20:27 +02:00
/**
* @var
*/
protected $currentRow;
2013-09-12 11:20:27 +02:00
/**
* @var string
*/
protected $file;
2013-09-21 22:17:54 +02:00
/**
* @var int
*/
protected $lineNumber;
2013-09-12 11:20:27 +02:00
/**
* @param string $file
*/
public function __construct($file)
{
2013-09-12 11:20:27 +02:00
$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"
2013-09-21 22:17:54 +02:00
*
* One cannot see the point of iterator pattern if you iterate on $this.
2013-09-21 22:17:54 +02:00
* This example is unclear and mixed with some Composite pattern ideas.
*/
foreach ($this as $line => $row) {
$row->process();
}
}
2013-09-21 22:17:54 +02:00
/**
* {@inheritdoc}
*/
public function rewind()
{
2013-09-12 11:20:27 +02:00
// seek to first line from $this->file
}
2013-09-21 22:17:54 +02:00
/**
* {@inheritdoc}
*/
public function next()
{
2013-09-12 11:20:27 +02:00
// read the next line from $this->file
if (!$eof) {
$data = ''; // get the line
2013-09-12 11:20:27 +02:00
$this->currentRow = new Row($data);
} else {
2013-09-12 11:20:27 +02:00
$this->currentRow = null;
}
}
2013-09-21 22:17:54 +02:00
/**
* {@inheritdoc}
*/
public function current()
{
2013-09-12 11:20:27 +02:00
return $this->currentRow;
}
2013-09-21 22:17:54 +02:00
/**
* {@inheritdoc}
*/
public function valid()
{
2013-09-12 11:20:27 +02:00
return null !== $this->currentRow;
}
2013-09-21 22:17:54 +02:00
/**
* {@inheritdoc}
*/
public function key()
{
// you would want to increment this in next() or whatsoever
2013-09-21 22:17:54 +02:00
return $this->lineNumber;
}
2013-07-03 08:39:51 +02:00
}