Skip to content

Instantly share code, notes, and snippets.

@jaytaph
Created December 4, 2011 17:16
Show Gist options
  • Save jaytaph/1430725 to your computer and use it in GitHub Desktop.
Save jaytaph/1430725 to your computer and use it in GitHub Desktop.
Examples for the iteratorAggregate blog
<?php
/*
* Example 1: Using iteratorAggregate
*/
// Simple class that represents our chapter
class Chapter {
protected $_title;
protected $_content;
function __construct($title, $content) {
$this->_title = $title;
$this->_content = $content;
}
function getTitle() {
return $this->_title;
}
function getContent() {
return $this->_content;
}
}
// Our book class. We can still iterate over our chapters with the
// help of the iteratorAggregate implementation.
class Book implements IteratorAggregate {
protected $_title;
protected $_author;
protected $_chapters;
function __construct($title, $author) {
$this->_title = $title;
$this->_author = $author;
$this->_chapter = array();
}
// This method must be implemented. It will return the actual iterator
function getIterator()
{
// This will return the articles. Since they are inside an array, we
// can use the standard array-iterator.
return new ArrayIterator($this->_chapters);
}
// Add a new chapter to this book
function addChapter(Chapter $chapter) {
$this->_chapters[] = $chapter;
}
function getTitle() {
return $this->_title;
}
function getAuthor() {
return $this->_author;
}
}
// Create a new book and add chapters to it
$book = new Book("About the iteratorAggregate", "Joshua Thijssen");
$book->addChapter(new Chapter("Foreword", "This is the introduction"));
$book->addChapter(new Chapter("Chapter 1", "Content"));
$book->addChapter(new Chapter("Chapter 2", "Content"));
print "All chapters from the book '" . $book->getTitle() . "', written by ".$book->getAuthor()." :" . PHP_EOL;
foreach ($book as $chapter) {
print "- " . $chapter->getTitle() . PHP_EOL;
}
// Add another chapter to our book
$book->addChapter(new Chapter("Epilogue", "Famous last words"));
print "All chapters from the book '" . $book->getTitle() . "', written by ".$book->getAuthor()." :" . PHP_EOL;
foreach ($book as $chapter) {
print "- " . $chapter->getTitle() . PHP_EOL;
}
/*
* Example 2: Using iteratorIterator to apply filtering
*/
// "change" our iteratoraggregate into a iterator.
$it = new IteratorIterator($book);
// Display the first two chapters only
$it = new LimitIterator($it, 0, 2);
foreach ($it as $chapter) {
print "- " . $chapter->getTitle() . PHP_EOL;
}
@shochdoerfer
Copy link

Very well done my friend!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment