SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
Generating
Power with Yield/Jason Myers @jasonamyers
Yield, a modern language love
story
Originally Proposed in 1995, the yield keyword became official via the
RFP on June 20th 2013 with PHP 5.5.Generators
Facebook said a Hip, Hop and Don't Stop, and did their own yield
generators in HipHop PHP
They are HEAVILY BASED off of Python, with a nod towards the
Mozilla JS implementation and the await C# concept.
Iterator
An object that lets us traverse a container
PHP Iterator Interface
Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}
For example checkout classArrayIterator
ArrayIterator Example
$fruits = array(
"apple" => "yummy",
"orange" => "ah ya, nice",
"grape" => "wow, I love it!",
"plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();
echo "Iterating over: " . $obj->count() . " valuesn";
while( $it->valid() )
{
echo $it->key() . "=" . $it->current() . "n";
$it->next();
}
Iterating over: 4 values
apple=yummy
orange=ah ya, nice
grape=wow, I love it!
plum=nah, not me
Generator
a special routine that can be used to control the iteration behavior of
a loop, and yields the values one at a time
TL;DR
A generator looks like a function but behaves like an iterator
Performant?
range(0, 1000000)
Uses over 100MB of RAM
Generator Version
function xrange($start, $limit, $step = 1) {
if ($start < $limit) {
if ($step <= 0) {
throw new LogicException('Step must be +ve');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be -ve');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
uses less than 1KB!
TL; DR
function xrange($min, $max) {
for ($i = $min; $i < $max; $i++) {
yield $i;
}
}
Sequences
function collatz($val) {
yield $val;
while ($val != 1) {
if ($val%2 == 0) {
$val /= 2;
} else {
$val = 3*$val + 1;
}
yield $val;
}
}
foreach (collatz(11) as $c) {
echo $c," ";
}
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Y U Only LOOPin?
It will work for any function that takes an Iterator or a Traversable as
argument
$arr = iterator_to_array(collatz(11));
Transformations
function multiply_sequence($a, $fac) {
foreach ($a as $val) {
yield $val*$fac;
}
}
function to_html_list($input) {
foreach ($input as $val) {
yield "<li>".$val."</li>";
}
}
Chaining
foreach (to_html_list(multiply_sequence(collatz(5),2)) as $val) {
echo $val,"n";
}
<li>10</li>
<li>32</li>
<li>16</li>
<li>8</li>
<li>4</li>
<li>2</li>
Selections
function select_pattern($input, $pattern) {
foreach ($input as $val) {
if (preg_match($pattern, $val)) {
yield $val;
}
}
}
Breath In
function getLines($file) {
$f = fopen($file, 'r');
if (!$f) {
throw new Exception();
}
while ($line = fgets($f)) {
yield $line;
}
fclose($f);
}
foreach (getLines("someFile") as $line) {
doSomethingWithLine($line);
}
Breath Out
function createLog($file) {
$f = fopen($file, 'a');
while (true) {
$line = yield;
fwrite($f, $line);
}
}
$log = createLog($file);
$log->send("First");
$log->send("Second");
$log->send("Third");
Bro Remote Me!
Fake the simultaneous processing of data
Green Threads
threads that are scheduled by a virtual machine (VM/interperter?)
instead of natively by the underlying operating system
function step1() {
$f = fopen("file.txt", 'r');
while ($line = fgets($f)) {
processLine($line);
yield true;
}
}
function step2() {
$f = fopen("file2.txt", 'r');
while ($line = fgets($f)) {
processLine($line);
yield true;
}
}
function step3() {
$f = fsockopen("www.example.com", 80);
stream_set_blocking($f, false);
$headers = "GET / HTTP/1.1rn";
$headers .= "Host: www.example.comrn";
$headers .= "Connection: Closernrn";
fwrite($f, $headers);
$body = '';
while (!feof($f)) {
$body .= fread($f, 8192);
yield true;
}
processBody($body);
}
function runner(array $steps) {
while (true) {
foreach ($steps as $key => $step) {
$step->next();
if (!$step->valid()) {
unset($steps[$key]);
}
}
if (empty($steps)) return;
}
}
runner(array(step1(), step2(), step3()));
ZOMG... THERE BE DRAGONS!
This relies on making sure we have no blocking IO
overREACTPHP much?
event based, non-blocking IO - ReActPHP
One More Thing
So if I can flip control, I can haz an Async?
class Buffer {
protected $reads, $data;
public function __construct() {
$this->reads = new SplQueue();
$this->data = new SplQueue();
}
public function read() {
if( $this->data->isEmpty() ) {
$deferred = new ReactPromiseDeferred();
$this->reads->enqueue($deferred->resolver());
return $deferred->promise();
} else {
return ReactPromiseWhen::resolve($this->data->dequeue());
}
}
public function write($str) {
if( $this->reads->isEmpty() ) {
$this->data->enqueue($str);
} else {
$this->reads->dequeue()->resolve($str);
}
}
}
function printer(Buffer $buffer) {
while( true ) {
$value = ( yield Util::async($buffer->read()) );
echo "Printer: ", $value, PHP_EOL;
yield Util::async(nested_printer($buffer));
}
}
function nested_printer(Buffer $buffer) {
for( $i = 0; $i < 5; $i++ ) {
// Yield a promise task and wait for the result - this is non-blocking
$value = ( yield Util::async($buffer->read()) );
echo "Nested printer: ", $value, PHP_EOL;
}
}
$buffer = new Buffer();
$scheduler = new AsyncScheduler();
$scheduler->add(new AsyncTaskGeneratorTask(printer($buffer)));
$i = 0;
$scheduler->add(new AsyncTaskRecurringTask(
function() use($buffer, &$i) { $buffer->write(++$i); }
));
$scheduler->run();
Printer: 1
Nested printer: 2
Nested printer: 3
Nested printer: 4
Nested printer: 5
Nested printer: 6
Printer: 7
Nested printer: 8
Nested printer: 9
Nested printer: 10
Nested printer: 11
Nested printer: 12
...
$loop = ReactEventLoopFactory::create();
$scheduler = new AsyncScheduler();
$scheduler->add(new AsyncTaskRecurringTask([$loop, 'tick']));
$scheduler->run();
Async
Created by Matt Pryor, on Bitbucket
Thanks
Huge thanks to Paul M. Jones and William Golden!
THE END
@jasonamyers

Más contenido relacionado

La actualidad más candente

Example code for the SADI BMI Calculator Web Service
Example code for the SADI BMI Calculator Web ServiceExample code for the SADI BMI Calculator Web Service
Example code for the SADI BMI Calculator Web ServiceMark Wilkinson
 
Isset(), unset(), empty() 4
Isset(), unset(), empty()   4Isset(), unset(), empty()   4
Isset(), unset(), empty() 4Reed Crouch
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suckerockendude
 
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...Matheus Marabesi
 
ZCPE - PHP Conference 2015
ZCPE   - PHP Conference 2015ZCPE   - PHP Conference 2015
ZCPE - PHP Conference 2015Matheus Marabesi
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - phpHung-yu Lin
 
02 - Second meetup
02 - Second meetup02 - Second meetup
02 - Second meetupEdiPHP
 
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
 
De 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKDe 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKAdolfo Sanz De Diego
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1兎 伊藤
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 

La actualidad más candente (20)

Example code for the SADI BMI Calculator Web Service
Example code for the SADI BMI Calculator Web ServiceExample code for the SADI BMI Calculator Web Service
Example code for the SADI BMI Calculator Web Service
 
Isset(), unset(), empty() 4
Isset(), unset(), empty()   4Isset(), unset(), empty()   4
Isset(), unset(), empty() 4
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
 
ZCPE - PHP Conference 2015
ZCPE   - PHP Conference 2015ZCPE   - PHP Conference 2015
ZCPE - PHP Conference 2015
 
Web 9 | OOP in PHP
Web 9 | OOP in PHPWeb 9 | OOP in PHP
Web 9 | OOP in PHP
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Web 4 | Core JavaScript
Web 4 | Core JavaScriptWeb 4 | Core JavaScript
Web 4 | Core JavaScript
 
02 - Second meetup
02 - Second meetup02 - Second meetup
02 - Second meetup
 
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
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
De 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWKDe 0 a 100 con Bash Shell Scripting y AWK
De 0 a 100 con Bash Shell Scripting y AWK
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1
 
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
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 

Similar a Generating Power with Yield

JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
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
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?Radek Benkel
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyoエラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyoShohei Okada
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
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
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPBradley Holt
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)Win Yu
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challengervanphp
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboardsDenis Ristic
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console componentHugo Hamon
 

Similar a Generating Power with Yield (20)

JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
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
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyoエラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
 
Functional php
Functional phpFunctional php
Functional php
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
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?
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challenger
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
 

Más de Jason Myers

Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis ToolsJason Myers
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMJason Myers
 
Filling the flask
Filling the flaskFilling the flask
Filling the flaskJason Myers
 
Building CLIs that Click
Building CLIs that ClickBuilding CLIs that Click
Building CLIs that ClickJason Myers
 
Spanning Tree Algorithm
Spanning Tree AlgorithmSpanning Tree Algorithm
Spanning Tree AlgorithmJason Myers
 
Introduction to Pandas
Introduction to PandasIntroduction to Pandas
Introduction to PandasJason Myers
 
SQLAlchemy Core: An Introduction
SQLAlchemy Core: An IntroductionSQLAlchemy Core: An Introduction
SQLAlchemy Core: An IntroductionJason Myers
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsJason Myers
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarJason Myers
 
Selenium testing
Selenium testingSelenium testing
Selenium testingJason Myers
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersJason Myers
 

Más de Jason Myers (11)

Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis Tools
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Building CLIs that Click
Building CLIs that ClickBuilding CLIs that Click
Building CLIs that Click
 
Spanning Tree Algorithm
Spanning Tree AlgorithmSpanning Tree Algorithm
Spanning Tree Algorithm
 
Introduction to Pandas
Introduction to PandasIntroduction to Pandas
Introduction to Pandas
 
SQLAlchemy Core: An Introduction
SQLAlchemy Core: An IntroductionSQLAlchemy Core: An Introduction
SQLAlchemy Core: An Introduction
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So Far
 
Selenium testing
Selenium testingSelenium testing
Selenium testing
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for Developers
 

Último

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
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
 
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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Último (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
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
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Generating Power with Yield

  • 2. Yield, a modern language love story Originally Proposed in 1995, the yield keyword became official via the RFP on June 20th 2013 with PHP 5.5.Generators Facebook said a Hip, Hop and Don't Stop, and did their own yield generators in HipHop PHP
  • 3. They are HEAVILY BASED off of Python, with a nod towards the Mozilla JS implementation and the await C# concept.
  • 4.
  • 5.
  • 6. Iterator An object that lets us traverse a container
  • 7.
  • 8. PHP Iterator Interface Iterator extends Traversable { /* Methods */ abstract public mixed current ( void ) abstract public scalar key ( void ) abstract public void next ( void ) abstract public void rewind ( void ) abstract public boolean valid ( void ) } For example checkout classArrayIterator
  • 9. ArrayIterator Example $fruits = array( "apple" => "yummy", "orange" => "ah ya, nice", "grape" => "wow, I love it!", "plum" => "nah, not me" ); $obj = new ArrayObject( $fruits ); $it = $obj->getIterator(); echo "Iterating over: " . $obj->count() . " valuesn"; while( $it->valid() ) { echo $it->key() . "=" . $it->current() . "n"; $it->next(); } Iterating over: 4 values apple=yummy orange=ah ya, nice grape=wow, I love it! plum=nah, not me
  • 10. Generator a special routine that can be used to control the iteration behavior of a loop, and yields the values one at a time
  • 11. TL;DR A generator looks like a function but behaves like an iterator
  • 12.
  • 14.
  • 15. Generator Version function xrange($start, $limit, $step = 1) { if ($start < $limit) { if ($step <= 0) { throw new LogicException('Step must be +ve'); } for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } else { if ($step >= 0) { throw new LogicException('Step must be -ve'); } for ($i = $start; $i >= $limit; $i += $step) { yield $i; } } } uses less than 1KB!
  • 16. TL; DR function xrange($min, $max) { for ($i = $min; $i < $max; $i++) { yield $i; } }
  • 17. Sequences function collatz($val) { yield $val; while ($val != 1) { if ($val%2 == 0) { $val /= 2; } else { $val = 3*$val + 1; } yield $val; } } foreach (collatz(11) as $c) { echo $c," "; } 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
  • 18.
  • 19. Y U Only LOOPin? It will work for any function that takes an Iterator or a Traversable as argument $arr = iterator_to_array(collatz(11));
  • 20. Transformations function multiply_sequence($a, $fac) { foreach ($a as $val) { yield $val*$fac; } } function to_html_list($input) { foreach ($input as $val) { yield "<li>".$val."</li>"; } }
  • 21. Chaining foreach (to_html_list(multiply_sequence(collatz(5),2)) as $val) { echo $val,"n"; } <li>10</li> <li>32</li> <li>16</li> <li>8</li> <li>4</li> <li>2</li>
  • 22. Selections function select_pattern($input, $pattern) { foreach ($input as $val) { if (preg_match($pattern, $val)) { yield $val; } } }
  • 23. Breath In function getLines($file) { $f = fopen($file, 'r'); if (!$f) { throw new Exception(); } while ($line = fgets($f)) { yield $line; } fclose($f); } foreach (getLines("someFile") as $line) { doSomethingWithLine($line); }
  • 24. Breath Out function createLog($file) { $f = fopen($file, 'a'); while (true) { $line = yield; fwrite($f, $line); } } $log = createLog($file); $log->send("First"); $log->send("Second"); $log->send("Third");
  • 25.
  • 26. Bro Remote Me! Fake the simultaneous processing of data
  • 27.
  • 28. Green Threads threads that are scheduled by a virtual machine (VM/interperter?) instead of natively by the underlying operating system
  • 29. function step1() { $f = fopen("file.txt", 'r'); while ($line = fgets($f)) { processLine($line); yield true; } }
  • 30. function step2() { $f = fopen("file2.txt", 'r'); while ($line = fgets($f)) { processLine($line); yield true; } }
  • 31. function step3() { $f = fsockopen("www.example.com", 80); stream_set_blocking($f, false); $headers = "GET / HTTP/1.1rn"; $headers .= "Host: www.example.comrn"; $headers .= "Connection: Closernrn"; fwrite($f, $headers); $body = ''; while (!feof($f)) { $body .= fread($f, 8192); yield true; } processBody($body); }
  • 32. function runner(array $steps) { while (true) { foreach ($steps as $key => $step) { $step->next(); if (!$step->valid()) { unset($steps[$key]); } } if (empty($steps)) return; } } runner(array(step1(), step2(), step3()));
  • 33. ZOMG... THERE BE DRAGONS! This relies on making sure we have no blocking IO
  • 34. overREACTPHP much? event based, non-blocking IO - ReActPHP
  • 35. One More Thing So if I can flip control, I can haz an Async?
  • 36. class Buffer { protected $reads, $data; public function __construct() { $this->reads = new SplQueue(); $this->data = new SplQueue(); } public function read() { if( $this->data->isEmpty() ) { $deferred = new ReactPromiseDeferred(); $this->reads->enqueue($deferred->resolver()); return $deferred->promise(); } else { return ReactPromiseWhen::resolve($this->data->dequeue()); } } public function write($str) { if( $this->reads->isEmpty() ) { $this->data->enqueue($str); } else { $this->reads->dequeue()->resolve($str); } } }
  • 37. function printer(Buffer $buffer) { while( true ) { $value = ( yield Util::async($buffer->read()) ); echo "Printer: ", $value, PHP_EOL; yield Util::async(nested_printer($buffer)); } }
  • 38. function nested_printer(Buffer $buffer) { for( $i = 0; $i < 5; $i++ ) { // Yield a promise task and wait for the result - this is non-blocking $value = ( yield Util::async($buffer->read()) ); echo "Nested printer: ", $value, PHP_EOL; } }
  • 39. $buffer = new Buffer(); $scheduler = new AsyncScheduler(); $scheduler->add(new AsyncTaskGeneratorTask(printer($buffer))); $i = 0; $scheduler->add(new AsyncTaskRecurringTask( function() use($buffer, &$i) { $buffer->write(++$i); } )); $scheduler->run(); Printer: 1 Nested printer: 2 Nested printer: 3 Nested printer: 4 Nested printer: 5 Nested printer: 6 Printer: 7 Nested printer: 8 Nested printer: 9 Nested printer: 10 Nested printer: 11 Nested printer: 12 ...
  • 40. $loop = ReactEventLoopFactory::create(); $scheduler = new AsyncScheduler(); $scheduler->add(new AsyncTaskRecurringTask([$loop, 'tick'])); $scheduler->run();
  • 41. Async Created by Matt Pryor, on Bitbucket
  • 42. Thanks Huge thanks to Paul M. Jones and William Golden!