SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Dernier (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

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