SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler 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!

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

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