SlideShare a Scribd company logo
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

PHP pod mikroskopom
PHP pod mikroskopomPHP pod mikroskopom
PHP pod mikroskopom
Saša Stamenković
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
Inbal 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 Php
JH Lee
 
Tax management-system
Tax management-systemTax management-system
Tax management-system
Fahim Faysal Kabir
 
Not Really PHP by the book
Not Really PHP by the bookNot Really PHP by the book
Not Really PHP by the book
Ryan 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ähe
Ralph Winzinger
 
Php Mysql
Php Mysql Php Mysql
Php Mysql
Mudasir Syed
 
Pagination in PHP
Pagination in PHPPagination in PHP
Pagination in PHP
Vineet Kumar Saini
 
Country State City Dropdown in PHP
Country State City Dropdown in PHPCountry State City Dropdown in PHP
Country State City Dropdown in PHP
Vineet 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 PHP
Vineet 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
 
Password.php
Password.phpPassword.php
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
Matheus 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 PHP
Yogesh singh
 
Threading
ThreadingThreading
Threading
b290572
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
Matheus Marabesi
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tiny
waniji
 
Information Science Blog Aggregation
Information Science Blog AggregationInformation Science Blog Aggregation
Information Science Blog Aggregation
Franny Gaede
 
Php
PhpPhp

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 developers
Stoyan 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 UnCon
Rafael Dohms
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo 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 it
Rafael Dohms
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri 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 Functions
David 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 / XSolve
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?
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 it
Rafael 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 2012
Rafael Dohms
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
brian 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 it
Rafael Dohms
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
Hugo Hamon
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
Taras Kalapun
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
Radek Benkel
 
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 Calisthenics
Guilherme Blanco
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
David Stockton
 
Oops in php
Oops in phpOops in php

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

Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 

Recently uploaded (20)

Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 

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);