SlideShare a Scribd company logo
Looping the
Loop with
SPL
Iterators
Looping the Loop with SPL
Iterators
What is an Iterator?
An Iterator is an object that enables a programmer to
traverse a container, particularly lists.
Looping the Loop with SPL
Iterators
What is an Iterator?
$dataSet = ['A', 'B', 'C'];
foreach($dataSet as $key => $value) {
echo "{$key} => {$value}", PHP_EOL;
}
Looping the Loop with SPL
Iterators
What is an Iterator?
0 => A
1 => B
2 => C
Looping the Loop with SPL
Iterators
What is an Iterator?
$data = ['A', 'B', 'C'];
$dataSet = new ArrayIterator($data);
foreach($dataSet as $key => $value) {
echo "{$key} => {$value}", PHP_EOL;
}
Looping the Loop with SPL
Iterators
What is an Iterator?
0 => A
1 => B
2 => C
Looping the Loop with SPL
Iterators
What is an Iterator?
interface Iterator extends Traversable {
/* Methods */
abstract public current ( void ) : mixed
abstract public key ( void ) : scalar
abstract public next ( void ) : void
abstract public rewind ( void ) : void
abstract public valid ( void ) : bool
}
Looping the Loop with SPL
Iterators
What is an Iterator?
$data = ['A', 'B', 'C’];
$iterator = new ArrayIterator($data);
$iterator->rewind();
while ($iterator->valid()) {
$key = $iterator->key();
$value = $iterator->current();
echo "{$key} => {$value}", PHP_EOL;
$iterator->next();
}
Looping the Loop with SPL
Iterators
What is an Iterator?
0 => A
1 => B
2 => C
Looping the Loop with SPL
Iterators
The Iterable Tree
iterable
array
Traversable
Iterator
Generator
IteratorAggregate
Looping the Loop with SPL
Iterators
The Iterable Tree
Not all iterables are equal
You can count the elements in an array !
Can you count the elements in an Iterator?
Looping the Loop with SPL
Iterators
The Iterable Tree
Not all iterables are equal
You can access the elements of an array by
their index !
Can you access the elements of an Iterator
by index ?
Looping the Loop with SPL
Iterators
The Iterable Tree
Not all iterables are equal
You can rewind an Iterator !
Can you rewind a Generator ?
Looping the Loop with SPL
Iterators
The Iterable Tree
Not all iterables are equal
Iterator_* functions (e.g. iterator_to_array)
work on Iterators ?
Can you use iterator_* functions on an
IteratorAggregate ?
Looping the Loop with SPL
Iterators
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
public function all(): array {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
$statement->execute();
$users = $statement->fetchAll();
return array_map(fn(array $user): User => User::fromArray($user), $users);
}
}
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
/**
* @return User[]
*/
public function all(): array {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
$statement->execute();
$users = $statement->fetchAll();
return array_map(fn(array $user): User => User::fromArray($user), $users);
}
}
Looping the Loop with SPL
Iterators
class UserList extends ArrayIterator {
}
Looping the Loop with SPL
Iterators
ArrayIterator
Implements:
Countable
ArrayAccess
Serializable
SeekableIterator (which entends Iterator)
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
public function all(): UserList {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
$statement->execute();
$users = $statement->fetchAll();
return new UserList(
array_map(fn(array $user): User => User::fromArray($user), $users)
);
}
}
Looping the Loop with SPL
Iterators
ArrayIterator
Implements:
Countable
Looping the Loop with SPL
Iterators
ArrayIterator – Countable
$userData = ['user1', 'user2', 'user3', 'user4'];
$userList = new UserList($userData);
$userCount = count($userList);
echo "There are {$userCount} users in this list", PHP_EOL;
Looping the Loop with SPL
Iterators
ArrayIterator – Countable
$userData = ['user1', 'user2', 'user3', 'user4'];
$userList = new UserList($userData);
echo "There are {$userList->count()} users in this list", PHP_EOL;
Looping the Loop with SPL
Iterators
ArrayIterator – Countable
There are 4 users in this list
Looping the Loop with SPL
Iterators
ArrayIterator
Implements:
Countable
ArrayAccess
Looping the Loop with SPL
Iterators
ArrayIterator – ArrayAccess
$userData = ['user1', 'user2', 'user3', 'user4'];
$userList = new UserList($userData);
echo "The 3rd entry in the list is {$userList[2]}", PHP_EOL;
Looping the Loop with SPL
Iterators
ArrayIterator – ArrayAccess
The 3rd entry in the list is user3
Looping the Loop with SPL
Iterators
ArrayIterator
Implements:
Countable
ArrayAccess
Serializable
Looping the Loop with SPL
Iterators
ArrayIterator – Serializable
$userData = ['user1', 'user2', 'user3', 'user4'];
$userList = new UserList($userData);
var_dump(serialize($userList));
Looping the Loop with SPL
Iterators
ArrayIterator – Serializable
string(117)
"O:8:"UserList":4:{i:0;i:0;i:1;a:4:{i:0;s:5:"user1";
i:1;s:5:"user2";i:2;s:5:"user3";i:3;s:5:"user4";}i:2;
a:0:{}i:3;N;}"
Looping the Loop with SPL
Iterators
ArrayIterator
Implements:
Countable
ArrayAccess
Serializable
SeekableIterator (which entends Iterator)
Looping the Loop with SPL
Iterators
ArrayIterator – SeekableIterator
$userData = ['user1', 'user2', 'user3', 'user4'];
$userList = new UserList($userData);
$userList->seek(2);
while ($userList->valid()) {
echo $userList->current(), PHP_EOL;
$userList->next();
}
Looping the Loop with SPL
Iterators
ArrayIterator – SeekableIterator
user3
user4
Looping the Loop with SPL
Iterators
ArrayIterator
Implements:
Countable
ArrayAccess
Serializable
SeekableIterator (which entends Iterator)
Also provides methods for sorting
Doesn’t work with array_* functions
Looping the Loop with SPL
Iterators
Looping the Loop with SPL
Iterators
Looping the Loop with SPL
Iterators
LimitIterator
$userData = ['user1', 'user2', 'user3', 'user4'];
$userList = new LimitIterator(
new UserList($userData),
2
);
foreach($userList as $value) {
echo $value, PHP_EOL;
}
Looping the Loop with SPL
Iterators
LimitIterator
user3
user4
Looping the Loop with SPL
Iterators
InfiniteIterator
$weekdayNames = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
$todayOffset = (int) (new DateTime('2020-09-08'))->format('w');
$workdayList = new LimitIterator(
new InfiniteIterator( new ArrayIterator($weekdayNames) ),
$todayOffset
);
$counter = 0;
foreach($workdayList as $dayOfWeek) {
echo $dayOfWeek, PHP_EOL;
if (++$counter === 14) break;
}
Looping the Loop with SPL
Iterators
InfiniteIterator
Tues
Wed
Thurs
Fri
Sat
Sun
Mon
Tues
Wed
Thurs
Fri
Sat
Sun
Mon
Looping the Loop with SPL
Iterators
CallbackFilterIterator
$weekdayNames = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
$todayOffset = (int) (new DateTime('2020-09-08'))->format('w');
$workdayList = new LimitIterator(
new CallbackFilterIterator(
new InfiniteIterator( new ArrayIterator($weekdayNames) ),
fn($dayName): bool => $dayName !== 'Sat' && $dayName !== 'Sun'
),
$todayOffset – 1
);
$counter = 0;
foreach($workdayList as $dayOfWeek) {
echo $dayOfWeek, PHP_EOL;
if (++$counter === 10) break;
}
Looping the Loop with SPL
Iterators
CallbackFilterIterator
Tues
Wed
Thurs
Fri
Mon
Tues
Wed
Thurs
Fri
Mon
Looping the Loop with SPL
Iterators
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
public function all(): UserList {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
$statement->execute();
$users = $statement->fetchAll();
return new UserList(
array_map(fn(array $user): User => User::fromArray($user), $users)
);
}
}
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
public function all(): Generator {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
$statement->execute();
while ($user = $statement->fetch()) {
yield User::fromArray($user);
}
}
}
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
/**
* @return Generator|User[]
*/
public function all(): Generator {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
$statement->execute();
while ($user = $statement->fetch()) {
yield User::fromArray($user);
}
}
}
Looping the Loop with SPL
Iterators
class UserList implements IteratorAggregate {
private PDOStatement $pdoStatement;
public function __construct(PDOStatement $pdoStatement) {
$this->pdoStatement = $pdoStatement;
}
public function getIterator(): Traversable {
$statement->execute();
while ($user = $this->pdoStatement->fetch()) {
yield User::fromArray($user);
}
}
}
Looping the Loop with SPL
Iterators
class UserRepository {
// ...
public function all(): UserList {
$userQuery = 'SELECT * FROM `users` ...';
$statement = $this->pdo->prepare($userQuery);
return new UserList($statement);
}
}
Looping the Loop with SPL
Iterators
Looping the Loop with SPL
Iterators
A Functional Guide to Cat Herding with PHP
Generators
https://markbakeruk.net/2016/01/19/a-functional-guide-to-cat-
herding-with-php-generators/
Looping the Loop with SPL
Iterators
Filtering and Mapping with SPL Iterators
https://markbakeruk.net/2020/01/05/filtering-and-mapping-with-
spl-iterators/
Looping the Loop with SPL
Iterators
Parallel Looping in PHP with SPL’s
MultipleIterator
https://markbakeruk.net/2019/12/31/parallel-looping-in-php-with-
spls-multipleiterator/
Looping the Loop with SPL
Iterators
Iterating PHP Iterators
By Cal Evans
https://leanpub.com/iteratingphpiterators
Looping the Loop with SPL
Iterators
Mastering the SPL Library
by Joshua Thijssen
https://www.phparch.com/books/mastering-the-spl-library/
Who am I?
Mark Baker
Senior Software Engineer
MessageBird BV, Amsterdam
Coordinator and Developer of:
Open Source PHPOffice library
PHPExcel, PHPWord, PHPPowerPoint, PHPProject, PHPVisio
Minor contributor to PHP core (SPL Datastructures)
Other small open source libraries available on github
@Mark_Baker
https://github.com/MarkBaker
http://uk.linkedin.com/pub/mark-baker/b/572/171
http://markbakeruk.net

More Related Content

What's hot

The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
Zend by Rogue Wave Software
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
XSolve
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 WorldFabien Potencier
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
Sérgio Rafael Siqueira
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
dcs plus
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
Jace Ju
 
Indices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceIndices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch Reference
Daniel Ku
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
Workhorse Computing
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
Mark Baker
 
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
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
Perforce
 

What's hot (20)

The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Indices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceIndices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch Reference
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
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
 
C99
C99C99
C99
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
 

Similar to Looping the Loop with SPL Iterators

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
Chris Tankersley
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
Matthieu Aubry
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
Gta v savegame
Gta v savegameGta v savegame
Gta v savegame
hozayfa999
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
PHP 8.1: Enums
PHP 8.1: EnumsPHP 8.1: Enums
PHP 8.1: Enums
Ayesh Karunaratne
 
Php Enums
Php EnumsPhp Enums
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Laravel
LaravelLaravel
Laravel
Sayed Ahmed
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
James Titcumb
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
James Titcumb
 
Solid principles
Solid principlesSolid principles
Solid principles
Bastian Feder
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHPHari K T
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 

Similar to Looping the Loop with SPL Iterators (20)

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Gta v savegame
Gta v savegameGta v savegame
Gta v savegame
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
PHP 8.1: Enums
PHP 8.1: EnumsPHP 8.1: Enums
PHP 8.1: Enums
 
Php Enums
Php EnumsPhp Enums
Php Enums
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Shell.php
Shell.phpShell.php
Shell.php
 
Laravel
LaravelLaravel
Laravel
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 
Solid principles
Solid principlesSolid principles
Solid principles
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 

More from Mark Baker

Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
A Brief History of Elephpants
A Brief History of ElephpantsA Brief History of Elephpants
A Brief History of Elephpants
Mark Baker
 
Aspects of love slideshare
Aspects of love slideshareAspects of love slideshare
Aspects of love slideshare
Mark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
Mark Baker
 
A Brief History of ElePHPants
A Brief History of ElePHPantsA Brief History of ElePHPants
A Brief History of ElePHPants
Mark Baker
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
Mark Baker
 
Anonymous classes2
Anonymous classes2Anonymous classes2
Anonymous classes2
Mark Baker
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
Mark Baker
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the Mask
Mark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
Mark Baker
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
Mark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
Mark Baker
 
Giving birth to an ElePHPant
Giving birth to an ElePHPantGiving birth to an ElePHPant
Giving birth to an ElePHPant
Mark Baker
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
Mark Baker
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
Mark Baker
 
Flying under the radar
Flying under the radarFlying under the radar
Flying under the radar
Mark Baker
 

More from Mark Baker (20)

Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
A Brief History of Elephpants
A Brief History of ElephpantsA Brief History of Elephpants
A Brief History of Elephpants
 
Aspects of love slideshare
Aspects of love slideshareAspects of love slideshare
Aspects of love slideshare
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
A Brief History of ElePHPants
A Brief History of ElePHPantsA Brief History of ElePHPants
A Brief History of ElePHPants
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Anonymous classes2
Anonymous classes2Anonymous classes2
Anonymous classes2
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the Mask
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
Giving birth to an ElePHPant
Giving birth to an ElePHPantGiving birth to an ElePHPant
Giving birth to an ElePHPant
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
 
Flying under the radar
Flying under the radarFlying under the radar
Flying under the radar
 

Recently uploaded

Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 

Recently uploaded (20)

Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 

Looping the Loop with SPL Iterators

  • 2. Looping the Loop with SPL Iterators What is an Iterator? An Iterator is an object that enables a programmer to traverse a container, particularly lists.
  • 3. Looping the Loop with SPL Iterators What is an Iterator? $dataSet = ['A', 'B', 'C']; foreach($dataSet as $key => $value) { echo "{$key} => {$value}", PHP_EOL; }
  • 4. Looping the Loop with SPL Iterators What is an Iterator? 0 => A 1 => B 2 => C
  • 5. Looping the Loop with SPL Iterators What is an Iterator? $data = ['A', 'B', 'C']; $dataSet = new ArrayIterator($data); foreach($dataSet as $key => $value) { echo "{$key} => {$value}", PHP_EOL; }
  • 6. Looping the Loop with SPL Iterators What is an Iterator? 0 => A 1 => B 2 => C
  • 7. Looping the Loop with SPL Iterators What is an Iterator? interface Iterator extends Traversable { /* Methods */ abstract public current ( void ) : mixed abstract public key ( void ) : scalar abstract public next ( void ) : void abstract public rewind ( void ) : void abstract public valid ( void ) : bool }
  • 8. Looping the Loop with SPL Iterators What is an Iterator? $data = ['A', 'B', 'C’]; $iterator = new ArrayIterator($data); $iterator->rewind(); while ($iterator->valid()) { $key = $iterator->key(); $value = $iterator->current(); echo "{$key} => {$value}", PHP_EOL; $iterator->next(); }
  • 9. Looping the Loop with SPL Iterators What is an Iterator? 0 => A 1 => B 2 => C
  • 10. Looping the Loop with SPL Iterators The Iterable Tree iterable array Traversable Iterator Generator IteratorAggregate
  • 11. Looping the Loop with SPL Iterators The Iterable Tree Not all iterables are equal You can count the elements in an array ! Can you count the elements in an Iterator?
  • 12. Looping the Loop with SPL Iterators The Iterable Tree Not all iterables are equal You can access the elements of an array by their index ! Can you access the elements of an Iterator by index ?
  • 13. Looping the Loop with SPL Iterators The Iterable Tree Not all iterables are equal You can rewind an Iterator ! Can you rewind a Generator ?
  • 14. Looping the Loop with SPL Iterators The Iterable Tree Not all iterables are equal Iterator_* functions (e.g. iterator_to_array) work on Iterators ? Can you use iterator_* functions on an IteratorAggregate ?
  • 15. Looping the Loop with SPL Iterators
  • 16. Looping the Loop with SPL Iterators class UserRepository { // ... public function all(): array { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); $statement->execute(); $users = $statement->fetchAll(); return array_map(fn(array $user): User => User::fromArray($user), $users); } }
  • 17. Looping the Loop with SPL Iterators class UserRepository { // ... /** * @return User[] */ public function all(): array { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); $statement->execute(); $users = $statement->fetchAll(); return array_map(fn(array $user): User => User::fromArray($user), $users); } }
  • 18. Looping the Loop with SPL Iterators class UserList extends ArrayIterator { }
  • 19. Looping the Loop with SPL Iterators ArrayIterator Implements: Countable ArrayAccess Serializable SeekableIterator (which entends Iterator)
  • 20. Looping the Loop with SPL Iterators class UserRepository { // ... public function all(): UserList { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); $statement->execute(); $users = $statement->fetchAll(); return new UserList( array_map(fn(array $user): User => User::fromArray($user), $users) ); } }
  • 21. Looping the Loop with SPL Iterators ArrayIterator Implements: Countable
  • 22. Looping the Loop with SPL Iterators ArrayIterator – Countable $userData = ['user1', 'user2', 'user3', 'user4']; $userList = new UserList($userData); $userCount = count($userList); echo "There are {$userCount} users in this list", PHP_EOL;
  • 23. Looping the Loop with SPL Iterators ArrayIterator – Countable $userData = ['user1', 'user2', 'user3', 'user4']; $userList = new UserList($userData); echo "There are {$userList->count()} users in this list", PHP_EOL;
  • 24. Looping the Loop with SPL Iterators ArrayIterator – Countable There are 4 users in this list
  • 25. Looping the Loop with SPL Iterators ArrayIterator Implements: Countable ArrayAccess
  • 26. Looping the Loop with SPL Iterators ArrayIterator – ArrayAccess $userData = ['user1', 'user2', 'user3', 'user4']; $userList = new UserList($userData); echo "The 3rd entry in the list is {$userList[2]}", PHP_EOL;
  • 27. Looping the Loop with SPL Iterators ArrayIterator – ArrayAccess The 3rd entry in the list is user3
  • 28. Looping the Loop with SPL Iterators ArrayIterator Implements: Countable ArrayAccess Serializable
  • 29. Looping the Loop with SPL Iterators ArrayIterator – Serializable $userData = ['user1', 'user2', 'user3', 'user4']; $userList = new UserList($userData); var_dump(serialize($userList));
  • 30. Looping the Loop with SPL Iterators ArrayIterator – Serializable string(117) "O:8:"UserList":4:{i:0;i:0;i:1;a:4:{i:0;s:5:"user1"; i:1;s:5:"user2";i:2;s:5:"user3";i:3;s:5:"user4";}i:2; a:0:{}i:3;N;}"
  • 31. Looping the Loop with SPL Iterators ArrayIterator Implements: Countable ArrayAccess Serializable SeekableIterator (which entends Iterator)
  • 32. Looping the Loop with SPL Iterators ArrayIterator – SeekableIterator $userData = ['user1', 'user2', 'user3', 'user4']; $userList = new UserList($userData); $userList->seek(2); while ($userList->valid()) { echo $userList->current(), PHP_EOL; $userList->next(); }
  • 33. Looping the Loop with SPL Iterators ArrayIterator – SeekableIterator user3 user4
  • 34. Looping the Loop with SPL Iterators ArrayIterator Implements: Countable ArrayAccess Serializable SeekableIterator (which entends Iterator) Also provides methods for sorting Doesn’t work with array_* functions
  • 35. Looping the Loop with SPL Iterators
  • 36. Looping the Loop with SPL Iterators
  • 37. Looping the Loop with SPL Iterators LimitIterator $userData = ['user1', 'user2', 'user3', 'user4']; $userList = new LimitIterator( new UserList($userData), 2 ); foreach($userList as $value) { echo $value, PHP_EOL; }
  • 38. Looping the Loop with SPL Iterators LimitIterator user3 user4
  • 39. Looping the Loop with SPL Iterators InfiniteIterator $weekdayNames = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat']; $todayOffset = (int) (new DateTime('2020-09-08'))->format('w'); $workdayList = new LimitIterator( new InfiniteIterator( new ArrayIterator($weekdayNames) ), $todayOffset ); $counter = 0; foreach($workdayList as $dayOfWeek) { echo $dayOfWeek, PHP_EOL; if (++$counter === 14) break; }
  • 40. Looping the Loop with SPL Iterators InfiniteIterator Tues Wed Thurs Fri Sat Sun Mon Tues Wed Thurs Fri Sat Sun Mon
  • 41. Looping the Loop with SPL Iterators CallbackFilterIterator $weekdayNames = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat']; $todayOffset = (int) (new DateTime('2020-09-08'))->format('w'); $workdayList = new LimitIterator( new CallbackFilterIterator( new InfiniteIterator( new ArrayIterator($weekdayNames) ), fn($dayName): bool => $dayName !== 'Sat' && $dayName !== 'Sun' ), $todayOffset – 1 ); $counter = 0; foreach($workdayList as $dayOfWeek) { echo $dayOfWeek, PHP_EOL; if (++$counter === 10) break; }
  • 42. Looping the Loop with SPL Iterators CallbackFilterIterator Tues Wed Thurs Fri Mon Tues Wed Thurs Fri Mon
  • 43. Looping the Loop with SPL Iterators
  • 44. Looping the Loop with SPL Iterators class UserRepository { // ... public function all(): UserList { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); $statement->execute(); $users = $statement->fetchAll(); return new UserList( array_map(fn(array $user): User => User::fromArray($user), $users) ); } }
  • 45. Looping the Loop with SPL Iterators class UserRepository { // ... public function all(): Generator { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); $statement->execute(); while ($user = $statement->fetch()) { yield User::fromArray($user); } } }
  • 46. Looping the Loop with SPL Iterators class UserRepository { // ... /** * @return Generator|User[] */ public function all(): Generator { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); $statement->execute(); while ($user = $statement->fetch()) { yield User::fromArray($user); } } }
  • 47. Looping the Loop with SPL Iterators class UserList implements IteratorAggregate { private PDOStatement $pdoStatement; public function __construct(PDOStatement $pdoStatement) { $this->pdoStatement = $pdoStatement; } public function getIterator(): Traversable { $statement->execute(); while ($user = $this->pdoStatement->fetch()) { yield User::fromArray($user); } } }
  • 48. Looping the Loop with SPL Iterators class UserRepository { // ... public function all(): UserList { $userQuery = 'SELECT * FROM `users` ...'; $statement = $this->pdo->prepare($userQuery); return new UserList($statement); } }
  • 49. Looping the Loop with SPL Iterators
  • 50. Looping the Loop with SPL Iterators A Functional Guide to Cat Herding with PHP Generators https://markbakeruk.net/2016/01/19/a-functional-guide-to-cat- herding-with-php-generators/
  • 51. Looping the Loop with SPL Iterators Filtering and Mapping with SPL Iterators https://markbakeruk.net/2020/01/05/filtering-and-mapping-with- spl-iterators/
  • 52. Looping the Loop with SPL Iterators Parallel Looping in PHP with SPL’s MultipleIterator https://markbakeruk.net/2019/12/31/parallel-looping-in-php-with- spls-multipleiterator/
  • 53. Looping the Loop with SPL Iterators Iterating PHP Iterators By Cal Evans https://leanpub.com/iteratingphpiterators
  • 54. Looping the Loop with SPL Iterators Mastering the SPL Library by Joshua Thijssen https://www.phparch.com/books/mastering-the-spl-library/
  • 55. Who am I? Mark Baker Senior Software Engineer MessageBird BV, Amsterdam Coordinator and Developer of: Open Source PHPOffice library PHPExcel, PHPWord, PHPPowerPoint, PHPProject, PHPVisio Minor contributor to PHP core (SPL Datastructures) Other small open source libraries available on github @Mark_Baker https://github.com/MarkBaker http://uk.linkedin.com/pub/mark-baker/b/572/171 http://markbakeruk.net