Iterator Design Pattern - files.meetup.comfiles.meetup.com/120908/Iterator Presentation.pdf ·...

Post on 15-Jul-2020

11 views 0 download

Transcript of Iterator Design Pattern - files.meetup.comfiles.meetup.com/120908/Iterator Presentation.pdf ·...

Iterator Design Patternin PHP5 with help from the SPL

presented on June 4th, 2009 for Seattle PHP Meetup by darcy w. christ

darcy@1000camels.com (email/jabber/msn)@1000camels (twitter)

Thursday, June 11, 2009

Iterator Pattern Defined

• The Iterator Pattern provides a way to access the elements of an aggregate object* sequentially without exposing its underlying representation.

* An aggregate object is one which contains other objects

Thursday, June 11, 2009

In other words...

• An iterator object encapsulates the internal structure of how the iteration occurs.

Thursday, June 11, 2009

In other words...

• An iterator object encapsulates the internal structure of how the iteration occurs.

• The simplest iterator has a "next element" method, which returns elements in some sequential order until there are no more.

Thursday, June 11, 2009

In other words...

• An iterator object encapsulates the internal structure of how the iteration occurs.

• The simplest iterator has a "next element" method, which returns elements in some sequential order until there are no more.

• More sophisticated iterators might allow several directions and types of movement through a complex structure.

Thursday, June 11, 2009

In other words...

Typically an iterator has three tasks that might or might not be implemented in separate methods:

Thursday, June 11, 2009

In other words...

• Testing whether elements are available

Typically an iterator has three tasks that might or might not be implemented in separate methods:

Thursday, June 11, 2009

In other words...

• Testing whether elements are available

• Advancing to the next n.th position

Typically an iterator has three tasks that might or might not be implemented in separate methods:

Thursday, June 11, 2009

In other words...

• Testing whether elements are available

• Advancing to the next n.th position

• Accessing the value at the current position

Typically an iterator has three tasks that might or might not be implemented in separate methods:

Thursday, June 11, 2009

TextIterator Class Diagram,

Iterator Class Diagram

Thursday, June 11, 2009

questions

how can i use this pattern in PHP?

am i going to have to create lots of obscure OO code to use this

pattern?

Thursday, June 11, 2009

No

answers

Yes

Thursday, June 11, 2009

Object Iteration

• PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with a foreach statement

• built-in to all objects

• can be extended using the SPL

Thursday, June 11, 2009

class MyClass { public $var1 = 'value 1'; public $var2 = 'value 2'; public $var3 = 'value 3';

protected $protectedVar = 'this is protected'; private $privateVar = 'this is private';}

Object Iteration

Thursday, June 11, 2009

$class = new MyClass();

foreach($class as $key => $value) { print "$key => $value\n";}

var1 => value 1var2 => value 2var3 => value 3

Output:

Object Iteration

Thursday, June 11, 2009

class MyClass { public $var1 = 'value 1'; public $var2 = 'value 2'; public $var3 = 'value 3';

protected $protectedVar = 'this is protected'; private $privateVar = 'this is private';

function iterateVisible() { echo "MyClass::iterateVisible:\n"; foreach($this as $key => $value) { print "$key => $value\n"; } }}

Object Iteration

Thursday, June 11, 2009

$class = new MyClass();

$class->iterateVisible();

MyClass::iterateVisible:var1 => value 1var2 => value 2var3 => value 3protectedVar => this is protectedprivateVar => this is private

Output:

Object Iteration

Thursday, June 11, 2009

interesting, but what else can i do?

Thursday, June 11, 2009

with a little help from the SPL, you can iterate through any list, regardless of what type of

list it is.

Thursday, June 11, 2009

Standard PHP Library (SPL)

• SPL is a collection of interfaces and classes that are meant to solve standard problems and implements some efficient data access interfaces and classes.

• created by Marcus Börger

• Very powerful (and poorly documented)

• Multiple classes and interfaces which deal with Iterators

Thursday, June 11, 2009

SPL Iterator AlgorithmsSPL offers some advanced iterator algorithms:

* interface RecursiveIterator extends Iterator * interface OuterIterator extends Iterator * class RecursiveIteratorIterator implements OuterIterator * abstract class FilterIterator implements OuterIterator * class ParentIterator extends FilterIterator implements RecursiveIterator * interface SeekableIterator extends Iterator * class LimitIterator implements OuterIterator * class CachingIterator implements OuterIterator * class RecursiveCachingIterator extends CachingIterator implements RecursiveIterator * class IteratorIterator implements OuterIterator * class NoRewindIterator implements OuterIterator * class EmptyIterator implements Iterator * class InfiniteIterator extends IteratorIterator * class AppendIterator implements OuterIterator * class RegexIterator extends FilterIterator * class RecursiveRegexIterator extends RegexIterator implements RecursiveIterator

Thursday, June 11, 2009

SPL Array Overloading

SPL offers advanced Array overloading:

* class ArrayObject implements IteratorAggregate, ArrayAccess, Countable * class ArrayIterator implements Iterator, ArrayAccess, Countable, SeekableIterator * class RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator

Thursday, June 11, 2009

PHP5 Iterator

rewind()while valid() { current() in $value key() in $key next()}

interface Iterator{ // Returns the current value function current(); // Returns the current key function key(); // Moves the internal pointer to the next element function next(); // Moves the internal pointer to the first element function rewind(); // If the current element is not at all valid (boolean) function valid();}

Thursday, June 11, 2009

Iterator & InteratorAggregate

$minmax = new MinMax(2, 6);

// calls $minmax->getIterator and // then iterates over the result foreach ($minmax as $v) {

print $v . "\n";}

class MinMaxIterator implements Iterator { protected $min, $max; protected $pos = 0; public function __construct($min, $max) { // we don't need to initialize pos here because rewind() is responsible for that $this->min = $min; $this->max = $max; } public function rewind() { // restart the looping process $this->pos = $this->min; } public function valid() { // test for end of loop return $this->pos <= $this->max; } public function key() { // php iterators are associative, but we don't provide a specialized key here return $this->pos; } public function current() { // access the current element return $this->pos; } public function next() { // advance to the next element $this->pos++; }}

class MinMax implements IteratorAggregate { protected $min, $max; public function __construct($min, $max) { $this->min = $min; $this->max = $max; } public function getIterator() { // creates an external iterator, called from foreach return new MinMaxIterator($this->min, $this->max); }}

Thursday, June 11, 2009

class ArrayObject

Output:

0 -> koala1 -> kangaroo2 -> wombat3 -> wallaby4 -> emu5 -> kiwi6 -> kookaburra7 -> platypus8 -> dingo

/*** a simple array ***/$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');

/*** create the array object ***/$arrayObj = new ArrayObject($array);

/*** append a value to the array ***/$arrayObj->append('dingo');

/*** iterate over the array ***/for($iterator = $arrayObj->getIterator(); /*** check if valid ***/ $iterator->valid(); /*** move to the next array member ***/ $iterator->next()){ /*** output the key and current array value ***/ echo $iterator->key() . ' -> ' . $iterator->current() . '<br />';}

The ArrayObject allows for external traversal of arrays and to create instances of ArrayIterator

class ArrayObject implements IteratorAggregate, Traversable, ArrayAccess, Countable

Thursday, June 11, 2009

class DirectoryIterator

try {$it = new DirectoryIterator('/home/fred');while( $it->valid()){

/*** if directory is not a dot directory ***/if( !$it->isDot() ) {

echo $it->current().': '.date('Y m d H:i:s', $it->getATime() ). '<br />';}/*** move to the next element ***/$it->next();

}}catch(Exception $e) {

/*** echo the error message ***/echo $e->getMessage();

}

now for a useful example

Output:

Pictures: 2009 06 04 11:55:40Downloads: 2009 06 04 11:55:40Documents: 2009 06 04 11:55:40

class DirectoryIterator extends SplFileInfo implements Iterator, Traversable, SeekableIterator

Thursday, June 11, 2009

interface ArrayAccess

class PHPMember implements ArrayAccess {public $firstName;public $lastName;public $joined;

public function offsetExists( $offset ) {return isset( $this->$offset );

}

public function offsetSet( $offset, $value) {$this->$offset = $value;

}

public function offsetGet( $offset ) {return $this->$offset;

}

public function offsetUnset( $offset ) {unset( $this->$offset );

}}

$member = new PHPMember();

/* set some properties like its an array */$member['firstName']= 'darcy';$member['lastName'] = 'christ';$member['joined'] = 20061101;

print_r($member);

Output:

Array( [firstName] => darcy [lastName] => christ [joined] => 20061101)

Treats an object like an Array

Thursday, June 11, 2009

Credits• Head First Design Patterns, Eric Freeman & Elizabeth Freeman, O’Reilly

• c2.com - Iterator Pattern- http://c2.com/cgi/wiki?IteratorPattern

• Wikipedia - Iterator Pattern- http://en.wikipedia.org/wiki/Iterator_pattern

• SitePoint.com - Introducing PHP 5's Standard Library, by Harry Fuecks - http://www.sitepoint.com/article/php5-standard-library/

• PHP.net - http://us3.php.net/manual/en/language.oop5.iterations.php- http://www.php.net/~helly/php/ext/spl/

• phpro.org - http://www.phpro.org/tutorials/Introduction-to-SPL.html

Thursday, June 11, 2009