SlideShare a Scribd company logo
1 of 37
Download to read offline
Uncovering Iterators
SJORS DE VALK
25 NOVEMBER 2010
ITERATORS (1)
∂ Black magic?
ITERATORS (2)
∂ Holy grail?
ITERATORS (3)
“An iterator is an object that allows a programmer
to traverse through all the elements of a
collection.”
∂ Wikipedia
ITERATORS (4)
$i = array(1, 2, 3);
reset($i);
while (current($i) !== false) {
echo key($values), current($values);
next($values);
}
∂ Array iteration (old school)
ITERATORS (5)
$i = new MyIterator();
$i->rewind();
while ($i->valid()) {
echo $i->key(), $i->current();
$i->next();
}
ITERATORS (6)
 rewind()
 valid()
 key()
 current()
 next()
∂ As defined by the Iterator interface
ITERATORS (7)
$i = new MyIterator();
foreach ($i as $key => $value) {
echo $key, $value;
}
∂ Methods are called automatically
BASICS (1)
$values = array(
‘Cameron Diaz’,
‘Alizée Jacotey’,
‘Britney Spears’,
‘Penélope Cruz’
);
BASICS (2)
class NaiveWomenIterator implements Iterator {
function __construct(array $values) {...}
function rewind() {...}
function valid() {...}
function key() {...}
function current() {...}
function next() {...}
}
BASICS (3)
class WomenIterator extends ArrayIterator {
// Nothing here
}
∂ Lean and mean
BASICS (4)
$i = new WomenIterator($values);
$i = new WomenFilterIterator($i);
foreach ($i as $name) {
echo $name;
}
BASICS (5)
class WomenFilterIterator extends FilterIterator {
function accept() {
return strpos($this->current(), ‘z’) !== false;
}
}
FIBONACCI (1)
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
FIBONACCI (2)
$previous = 1;
$current = 0;
while (true) {
echo $current;
$oldCurrent = $current;
$current += $previous;
$previous = $oldCurrent;
}
∂ Classic approach
FIBONACCI (3)
$i = new FibonacciIterator();
foreach ($i as $value) {
echo $value;
}
∂ Iterator approach: hides the implementation
FIBONACCI (4)
$i = new FibonacciIterator();
$i = new LimitIterator($i, 0, 50);
foreach ($i as $value) {
echo $value;
}
∂ No need to change the original iterator
WORDS (1)
$contents = loadFile(‘http://www.gutenberg…’);
$i = new NaiveWordIterator($contents);
foreach ($i as $word) {
echo $word;
}
WORDS (2)
$contents = loadFile(‘http://www.gutenberg…’);
$i = new CharacterIterator($contents);
$i = new WordIterator($i);
foreach ($i as $word) {
echo $word;
}
WORDS (3)
$contents = loadFile(‘http://www.gutenberg…’);
$i = new CharacterIterator($contents);
$i = new WordIterator($i);
$i = new RegexIterator($i, ‘/god/i’);
foreach ($i as $word) {
echo $word;
}
WORDS (4)
$contents = loadFile(‘http://www.gutenberg…’);
$i = new CharacterIterator($contents);
$i = new WordIterator($i);
$i = new RegexIterator($i, ‘/god/i’);
$i = new BigWordsFilterIterator($i, 5);
foreach ($i as $word) {
echo $word;
}
WORDS (5)
$contents = loadFile(‘http://www.gutenberg…’);
$i = new CharacterIterator($contents);
$i = new WordIterator($i);
$i = new WordFrequencyIterator($i);
foreach ($i as $word) {
echo $word;
}
WORDS (6)
$contents = loadFile(‘http://www.gutenberg…’);
$i = new CharacterIterator($contents);
$i = new WordIterator($i);
$i = new BigWordsFilterIterator($i, 10);
$i = new WordFrequencyIterator($i);
foreach ($i as $word) {
echo $word;
}
MP3 (1)
∂ Old school recursive directory iteration
function listFiles($path) {
$files = array();
$handle = opendir($path);
while (false !== ($file = readdir($handle))) {
$files[] = $file;
if (is_dir($path . ‘/’ . $file)) {
$files = array_merge($files, listFiles($path . ‘/’ . $file));
}
}
return $files;
}
MP3 (2)
∂ Lean and mean. Returns SplFileInfo
$i = new Mp3RecursiveDirectoryIterator($path);
foreach ($i as $file) {
echo $file->getFilename();
}
MP3 (3)
$i = new Mp3RecursiveDirectoryIterator($path);
function render(Iterator $i) {
echo $i->getDepth(), $i->getFilename();
return true;
}
iterator_apply($i, ‘render’, array($i));
MP3 (4)
$i = new Mp3RecursiveDirectoryIterator($path);
echo count($i); // Nope
echo $i->count(); // Nope
echo iterator_count($i);
MP3 (5)
$i = new Mp3RecursiveDirectoryIterator($path);
$i = new SongsIterator($i);
foreach ($i as $song) {
echo $song->title;
}
MP3 (6)
$i = new Mp3RecursiveDirectoryIterator($path);
$i = new SongsIterator($i);
foreach ($i as $song) {
foreach ($song as $property) {
echo $property; // E.g. title, artist
}
}
MP3 (7)
∂ No need for a toArray()
class Song implements IteratorAggregate {
function getIterator() {
return new ArrayIterator(
get_object_vars($this)
);
}
}
MP3 (8)
$i = new Mp3RecursiveDirectoryIterator($path);
$i = new Mp3ShortSongsFilterIterator($i);
foreach ($i as $file) {
echo $file->getFilename();
}
MP3 (9)
$i = new Mp3RecursiveDirectoryIterator($path);
$i = new Mp3ShortSongsFilterIterator($i);
$i = new InfiniteIterator($i);
foreach ($i as $file) {
echo $file->getFilename();
}
MOVIES (1)
$i = new ImdbTopMoviesIterator();
$i = new LimitIterator($i, 1, 10);
foreach ($i as $movie) {
echo $movie->rank, $movie->title;
}
MOVIES (2)
$i = new ImdbBoxOfficeMoviesIterator($url);
$i = new LimitIterator($i, 1, 10);
foreach ($i as $movie) {
echo $movie->rank, $movie->title;
}
MOVIES (3)
$x = new ImdbTopMoviesIterator();
$x = new LimitIterator($x, 1, 10);
$y= new ImdbBoxOfficeMoviesIterator($url);
$y = new LimitIterator($y, 1, 10);
$i = new MultipleIterator();
$i->attachIterator($x);
$i->attachIterator($y);
QUESTIONS?
∂ THANKS!

More Related Content

What's hot

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)Dennis Knochenwefel
 
C A S Sample Php
C A S Sample PhpC A S Sample Php
C A S Sample PhpJH Lee
 
Not Really PHP by the book
Not Really PHP by the bookNot Really PHP by the book
Not Really PHP by the bookRyan Kilfedder
 
Node.js - Demnächst auf einem Server in Ihrer Nähe
Node.js - Demnächst auf einem Server in Ihrer NäheNode.js - Demnächst auf einem Server in Ihrer Nähe
Node.js - Demnächst auf einem Server in Ihrer NäheRalph Winzinger
 
Country State City Dropdown in PHP
Country State City Dropdown in PHPCountry State City Dropdown in PHP
Country State City Dropdown in PHPVineet Kumar Saini
 
Add edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHPAdd edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHPVineet Kumar Saini
 
TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !Matheus Marabesi
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Matheus Marabesi
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHPYogesh singh
 
Threading
ThreadingThreading
Threadingb290572
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tinywaniji
 
Information Science Blog Aggregation
Information Science Blog AggregationInformation Science Blog Aggregation
Information Science Blog AggregationFranny Gaede
 

What's hot (20)

PHP pod mikroskopom
PHP pod mikroskopomPHP pod mikroskopom
PHP pod mikroskopom
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)
 
C A S Sample Php
C A S Sample PhpC A S Sample Php
C A S Sample Php
 
Tax management-system
Tax management-systemTax management-system
Tax management-system
 
Not Really PHP by the book
Not Really PHP by the bookNot Really PHP by the book
Not Really PHP by the book
 
Node.js - Demnächst auf einem Server in Ihrer Nähe
Node.js - Demnächst auf einem Server in Ihrer NäheNode.js - Demnächst auf einem Server in Ihrer Nähe
Node.js - Demnächst auf einem Server in Ihrer Nähe
 
Php Mysql
Php Mysql Php Mysql
Php Mysql
 
Pagination in PHP
Pagination in PHPPagination in PHP
Pagination in PHP
 
Country State City Dropdown in PHP
Country State City Dropdown in PHPCountry State City Dropdown in PHP
Country State City Dropdown in PHP
 
Add edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHPAdd edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHP
 
TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !
 
Password.php
Password.phpPassword.php
Password.php
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHP
 
Threading
ThreadingThreading
Threading
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tiny
 
Information Science Blog Aggregation
Information Science Blog AggregationInformation Science Blog Aggregation
Information Science Blog Aggregation
 
Php
PhpPhp
Php
 

Similar to Uncovering Iterators

JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsDavid Golden
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Lucas Witold Adamus
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Rafael Dohms
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tiebrian d foy
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console componentHugo Hamon
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHPTaras Kalapun
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Rafael Dohms
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of TransductionDavid Stockton
 

Similar to Uncovering Iterators (20)

JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)Your code sucks, let's fix it (CakeFest2012)
Your code sucks, let's fix it (CakeFest2012)
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
Oops in php
Oops in phpOops in php
Oops in php
 

Recently uploaded

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Uncovering Iterators

  • 1. Uncovering Iterators SJORS DE VALK 25 NOVEMBER 2010
  • 4. ITERATORS (3) “An iterator is an object that allows a programmer to traverse through all the elements of a collection.” ∂ Wikipedia
  • 5. ITERATORS (4) $i = array(1, 2, 3); reset($i); while (current($i) !== false) { echo key($values), current($values); next($values); } ∂ Array iteration (old school)
  • 6. ITERATORS (5) $i = new MyIterator(); $i->rewind(); while ($i->valid()) { echo $i->key(), $i->current(); $i->next(); }
  • 7. ITERATORS (6)  rewind()  valid()  key()  current()  next() ∂ As defined by the Iterator interface
  • 8. ITERATORS (7) $i = new MyIterator(); foreach ($i as $key => $value) { echo $key, $value; } ∂ Methods are called automatically
  • 9. BASICS (1) $values = array( ‘Cameron Diaz’, ‘Alizée Jacotey’, ‘Britney Spears’, ‘Penélope Cruz’ );
  • 10. BASICS (2) class NaiveWomenIterator implements Iterator { function __construct(array $values) {...} function rewind() {...} function valid() {...} function key() {...} function current() {...} function next() {...} }
  • 11. BASICS (3) class WomenIterator extends ArrayIterator { // Nothing here } ∂ Lean and mean
  • 12. BASICS (4) $i = new WomenIterator($values); $i = new WomenFilterIterator($i); foreach ($i as $name) { echo $name; }
  • 13. BASICS (5) class WomenFilterIterator extends FilterIterator { function accept() { return strpos($this->current(), ‘z’) !== false; } }
  • 14. FIBONACCI (1) Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
  • 15. FIBONACCI (2) $previous = 1; $current = 0; while (true) { echo $current; $oldCurrent = $current; $current += $previous; $previous = $oldCurrent; } ∂ Classic approach
  • 16. FIBONACCI (3) $i = new FibonacciIterator(); foreach ($i as $value) { echo $value; } ∂ Iterator approach: hides the implementation
  • 17. FIBONACCI (4) $i = new FibonacciIterator(); $i = new LimitIterator($i, 0, 50); foreach ($i as $value) { echo $value; } ∂ No need to change the original iterator
  • 18. WORDS (1) $contents = loadFile(‘http://www.gutenberg…’); $i = new NaiveWordIterator($contents); foreach ($i as $word) { echo $word; }
  • 19. WORDS (2) $contents = loadFile(‘http://www.gutenberg…’); $i = new CharacterIterator($contents); $i = new WordIterator($i); foreach ($i as $word) { echo $word; }
  • 20. WORDS (3) $contents = loadFile(‘http://www.gutenberg…’); $i = new CharacterIterator($contents); $i = new WordIterator($i); $i = new RegexIterator($i, ‘/god/i’); foreach ($i as $word) { echo $word; }
  • 21. WORDS (4) $contents = loadFile(‘http://www.gutenberg…’); $i = new CharacterIterator($contents); $i = new WordIterator($i); $i = new RegexIterator($i, ‘/god/i’); $i = new BigWordsFilterIterator($i, 5); foreach ($i as $word) { echo $word; }
  • 22. WORDS (5) $contents = loadFile(‘http://www.gutenberg…’); $i = new CharacterIterator($contents); $i = new WordIterator($i); $i = new WordFrequencyIterator($i); foreach ($i as $word) { echo $word; }
  • 23. WORDS (6) $contents = loadFile(‘http://www.gutenberg…’); $i = new CharacterIterator($contents); $i = new WordIterator($i); $i = new BigWordsFilterIterator($i, 10); $i = new WordFrequencyIterator($i); foreach ($i as $word) { echo $word; }
  • 24. MP3 (1) ∂ Old school recursive directory iteration function listFiles($path) { $files = array(); $handle = opendir($path); while (false !== ($file = readdir($handle))) { $files[] = $file; if (is_dir($path . ‘/’ . $file)) { $files = array_merge($files, listFiles($path . ‘/’ . $file)); } } return $files; }
  • 25. MP3 (2) ∂ Lean and mean. Returns SplFileInfo $i = new Mp3RecursiveDirectoryIterator($path); foreach ($i as $file) { echo $file->getFilename(); }
  • 26. MP3 (3) $i = new Mp3RecursiveDirectoryIterator($path); function render(Iterator $i) { echo $i->getDepth(), $i->getFilename(); return true; } iterator_apply($i, ‘render’, array($i));
  • 27. MP3 (4) $i = new Mp3RecursiveDirectoryIterator($path); echo count($i); // Nope echo $i->count(); // Nope echo iterator_count($i);
  • 28. MP3 (5) $i = new Mp3RecursiveDirectoryIterator($path); $i = new SongsIterator($i); foreach ($i as $song) { echo $song->title; }
  • 29. MP3 (6) $i = new Mp3RecursiveDirectoryIterator($path); $i = new SongsIterator($i); foreach ($i as $song) { foreach ($song as $property) { echo $property; // E.g. title, artist } }
  • 30. MP3 (7) ∂ No need for a toArray() class Song implements IteratorAggregate { function getIterator() { return new ArrayIterator( get_object_vars($this) ); } }
  • 31. MP3 (8) $i = new Mp3RecursiveDirectoryIterator($path); $i = new Mp3ShortSongsFilterIterator($i); foreach ($i as $file) { echo $file->getFilename(); }
  • 32. MP3 (9) $i = new Mp3RecursiveDirectoryIterator($path); $i = new Mp3ShortSongsFilterIterator($i); $i = new InfiniteIterator($i); foreach ($i as $file) { echo $file->getFilename(); }
  • 33. MOVIES (1) $i = new ImdbTopMoviesIterator(); $i = new LimitIterator($i, 1, 10); foreach ($i as $movie) { echo $movie->rank, $movie->title; }
  • 34. MOVIES (2) $i = new ImdbBoxOfficeMoviesIterator($url); $i = new LimitIterator($i, 1, 10); foreach ($i as $movie) { echo $movie->rank, $movie->title; }
  • 35. MOVIES (3) $x = new ImdbTopMoviesIterator(); $x = new LimitIterator($x, 1, 10); $y= new ImdbBoxOfficeMoviesIterator($url); $y = new LimitIterator($y, 1, 10); $i = new MultipleIterator(); $i->attachIterator($x); $i->attachIterator($y);