@adam_englander
Build A Bot Workshop:
Async Primer
Adam Englander
iovation
@adam_englander
What You Will Need
• PHP 7.0, or 7.1 (Examples will be 7.1)
• intl extension
• Twitter account
• Twitter Developer App: https://apps.twitter.com
• OAuth Credentials: https://dev.twitter.com/oauth/
overview/application-owner-access-tokens
@adam_englander
What We Will Discuss
• Concurrent Programming
• Asynchronous I/O
• AMPHP Asynchronous Framework for PHP
@adam_englander
What We Will Do
1. We will use an asynchronous HTTP client to
execute a Twitter REST API command.
2. We will use an asynchronous HTTP client to
process a continuous stream via the Twitter
User Stream API.
3. We will leverage both of the above to listen to a
topic and automatically respond to updates.
@adam_englander
Concurrent Programming
• Forking and Threading
• Asynchronous I/O
• Fork/Join
• Event Loop
Strategies Methodologies
@adam_englander
Forking and Threading
• Available in PHP core since PHP 4.1
• Requires the use of shared memory
• Requires code to be written for management of
forks/threads
• Creates separate copies of code for each
thread/fork
@adam_englander
Asynchronous I/O
• Frees up the current process while I/O is
performed
• Executes code based on I/O events
• No copying of code for separate process
@adam_englander
Asynchronous I/O Libraries
• Streams via stream_select and socket_select
• eio — libeio
• ev — libev
• libevent — libevent
• event — libevent
@adam_englander
Fork/Thread vs Async I/O
• Compute heavy
• Process isolation
• Non-Async library
• I/O processes
• Process/memory
optimization
Fork/Thread Async I/O
@adam_englander
Fork/Join Parallelism
S TA RT
P R O C E S S 1
P R O C E S S 2
P R O C E S S 3
E N DF O R K J O I N
Fork/Join Example
$dispatcher = new AmpThreadDispatcher();

$a = $dispatcher->call('slowProcess1');

$b = $dispatcher->call('slowProcess2');

$c = $dispatcher->call('slowProcess3');



$comboPromise = Ampall([$a, $b, $c]);

list($a, $b, $c) = Ampwait($comboPromise);
@adam_englander
Event Loop Parallelism
P R O C E S S
Q U E U E
I T E M
Q U E U E
I T E M
I N
Q U E U E ?
X
Yes
No
A S Y N C
P R O C E S S
A S Y N C
P R O C E S S
A S Y N C
P R O C E S S
A S Y N C
P R O C E S S
Event Loop Example
<?php

# Build objects to handle asynchronous interaction

$loop = ReactEventLoopFactory::create();

$dnsFactory = new ReactDnsResolverFactory();

$dns = $dnsFactory->createCached('8.8.8.8', $loop);

$factory = new ReactHttpClientFactory();

$client = $factory->create($loop, $dns);

$resp = array();
# Create callback for handling response

$responseHandler = function ($response) use ($resp) {

$response->on( 'data', function ($data) use ($resp) {

$resp[] = $data;

});

};
# Queue up requests to send

$request = $client->request('GET', 'http://www.timeapi.org/utc/now');

$request->on('response', $responseHandler);

$request->end();



$request = $client->request('GET', 'http://www.timeapi.org/utc/now');

$request->on('response', $responseHandler);

$request->end();



# Run the loop

$loop->run();
@adam_englander
Fork/Join vs Event Loop
• Enhance existing
synchronous apps
• Promises
• Hack/HHVM
• Non-HTTP apps
• Full async apps
• High volume apps
Fork/Join Event Loop
Callbacks vs. Generators
$stream = yield $apiClient->request($request);

while (null !== $message = yield $stream->read()) {

print($message[‘user’][‘screen_name’].": “.$message[‘text']);

}
Callback
Generator
Aerysrouter()

->get("/", function (AerysRequest $req, AerysResponse $resp) {

$resp->end("<h1>Hello World!</h1>");

})

->head("/", function (AerysRequest $req, AerysResponse $resp) {

$resp->end("<h1>Hello Head!</h1>");

});
@adam_englander
AMPHP
Asynchronous Framework for PHP
@adam_englander
Complete Modern Framework
• Modular framework segmented into logical parts
• Supersedes icicle.io
• Drivers for common storage engines
• Can be used for event loop and fork/join
• Can use threads or async i/o
@adam_englander
Code Time!
@adam_englander
• http://amphp.org/
• #amphp on Freenode IRC
• http://blog.kelunik.com/
• https://dev.twitter.com/
• https://github.com/PeeHaa/AsyncTwitter
• https://github.com/aenglander/amp-twitter-bot
Resources
@adam_englander
Please Rate Me
https://joind.in/talk/e9da4

More Related Content

PDF
Build a bot workshop async primer - php[tek]
PDF
Refactorización de aplicaciones PHP/Symfony2
KEY
Defly
PPTX
Introduction to testing in Rails
PDF
WP Weekend #2 - Corcel, aneb WordPress přes Laravel
DOCX
Cucumber testing
PPT
Perlbal Tutorial
Build a bot workshop async primer - php[tek]
Refactorización de aplicaciones PHP/Symfony2
Defly
Introduction to testing in Rails
WP Weekend #2 - Corcel, aneb WordPress přes Laravel
Cucumber testing
Perlbal Tutorial

What's hot (19)

PPTX
10 tips for making Bash a sane programming language
PDF
Lab 1: Compiler Toolchain
PDF
Gtg12
PDF
Practical Google App Engine Applications In Py
PDF
aautoPilot
PDF
Modern Perl Toolchain
ODP
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
PPTX
CodeIgniter Ant Scripting
PPTX
Code igniter unittest-part1
PDF
Design Summit - Rails 4 Migration - Aaron Patterson
PDF
Simplifying Code: Monster to Elegant in 5 Steps
KEY
Rails Antipatterns | Open Session with Chad Pytel
PDF
Gore: Go REPL
KEY
You're Doing It Wrong
PDF
第1回PHP拡張勉強会
PDF
Ansible Callback Plugins
PDF
Silex and Twig (PHP Dorset talk)
PPTX
You are not_hiding_from_me_.net
PPT
My GAE apps.
10 tips for making Bash a sane programming language
Lab 1: Compiler Toolchain
Gtg12
Practical Google App Engine Applications In Py
aautoPilot
Modern Perl Toolchain
Satellite Apps around the Cloud: Integrating your infrastructure with JIRA St...
CodeIgniter Ant Scripting
Code igniter unittest-part1
Design Summit - Rails 4 Migration - Aaron Patterson
Simplifying Code: Monster to Elegant in 5 Steps
Rails Antipatterns | Open Session with Chad Pytel
Gore: Go REPL
You're Doing It Wrong
第1回PHP拡張勉強会
Ansible Callback Plugins
Silex and Twig (PHP Dorset talk)
You are not_hiding_from_me_.net
My GAE apps.

Similar to ZendCon 2017 - Build a Bot Workshop - Async Primer (20)

ODP
Implementing Comet using PHP
PDF
ReactPHP
ODP
Incredible Machine with Pipelines and Generators
PPT
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
PPT
Php i basic chapter 3
PPT
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
PPTX
PSGI and Plack from first principles
PDF
Building Cloud Castles
KEY
Motion Django Meetup
KEY
Plack - LPW 2009
PPTX
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
PDF
Using Sinatra to Build REST APIs in Ruby
KEY
Rails Presentation (Anton Dmitriyev)
PDF
Rhebok, High Performance Rack Handler / Rubykaigi 2015
KEY
Psgi Plack Sfpm
KEY
Psgi Plack Sfpm
ODP
Intro To Spring Python
PPT
Heavy Web Optimization: Backend
PDF
Ruby HTTP clients comparison
PPTX
Async programming and python
Implementing Comet using PHP
ReactPHP
Incredible Machine with Pipelines and Generators
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
PSGI and Plack from first principles
Building Cloud Castles
Motion Django Meetup
Plack - LPW 2009
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
Using Sinatra to Build REST APIs in Ruby
Rails Presentation (Anton Dmitriyev)
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Psgi Plack Sfpm
Psgi Plack Sfpm
Intro To Spring Python
Heavy Web Optimization: Backend
Ruby HTTP clients comparison
Async programming and python

More from Adam Englander (20)

PPTX
Making PHP Smarter - Dutch PHP 2023.pptx
PDF
Practical API Security - PyCon 2019
PDF
Threat Modeling for Dummies
PDF
ZendCon 2018 - Practical API Security
PDF
ZendCon 2018 - Cryptography in Depth
PDF
Threat Modeling for Dummies - Cascadia PHP 2018
PDF
Dutch PHP 2018 - Cryptography for Beginners
PDF
php[tek] 2108 - Cryptography Advances in PHP 7.2
PDF
php[tek] 2018 - Biometrics, fantastic failure point of the future
PDF
Biometrics: Sexy, Secure and... Stupid - RSAC 2018
PPTX
Practical API Security - PyCon 2018
PDF
Practical API Security - Midwest PHP 2018
PDF
Cryptography for Beginners - Midwest PHP 2018
PDF
Cryptography for Beginners - Sunshine PHP 2018
PDF
ConFoo Vancouver 2017 - Biometrics: Fantastic Failure Point of the Future
PDF
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
PDF
ZendCon 2017 - Cryptography for Beginners
PDF
ZendCon 2017: The Red Team is Coming
PDF
Symfony Live San Franciso 2017 - BDD API Development with Symfony and Behat
PDF
Coder Cruise 2017 - The Red Team Is Coming
Making PHP Smarter - Dutch PHP 2023.pptx
Practical API Security - PyCon 2019
Threat Modeling for Dummies
ZendCon 2018 - Practical API Security
ZendCon 2018 - Cryptography in Depth
Threat Modeling for Dummies - Cascadia PHP 2018
Dutch PHP 2018 - Cryptography for Beginners
php[tek] 2108 - Cryptography Advances in PHP 7.2
php[tek] 2018 - Biometrics, fantastic failure point of the future
Biometrics: Sexy, Secure and... Stupid - RSAC 2018
Practical API Security - PyCon 2018
Practical API Security - Midwest PHP 2018
Cryptography for Beginners - Midwest PHP 2018
Cryptography for Beginners - Sunshine PHP 2018
ConFoo Vancouver 2017 - Biometrics: Fantastic Failure Point of the Future
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
ZendCon 2017 - Cryptography for Beginners
ZendCon 2017: The Red Team is Coming
Symfony Live San Franciso 2017 - BDD API Development with Symfony and Behat
Coder Cruise 2017 - The Red Team Is Coming

Recently uploaded (20)

PDF
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
PDF
Early detection and classification of bone marrow changes in lumbar vertebrae...
PDF
IT-ITes Industry bjjbnkmkhkhknbmhkhmjhjkhj
PDF
Data Virtualization in Action: Scaling APIs and Apps with FME
PDF
A symptom-driven medical diagnosis support model based on machine learning te...
PDF
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Launch a Bumble-Style App with AI Features in 2025.pdf
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
PDF
Build Real-Time ML Apps with Python, Feast & NoSQL
PDF
Co-training pseudo-labeling for text classification with support vector machi...
PDF
Human Computer Interaction Miterm Lesson
PDF
Decision Optimization - From Theory to Practice
PPTX
How to Convert Tickets Into Sales Opportunity in Odoo 18
PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PDF
Streamline Vulnerability Management From Minimal Images to SBOMs
PDF
CEH Module 2 Footprinting CEH V13, concepts
PDF
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
PDF
Identification of potential depression in social media posts
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
Early detection and classification of bone marrow changes in lumbar vertebrae...
IT-ITes Industry bjjbnkmkhkhknbmhkhmjhjkhj
Data Virtualization in Action: Scaling APIs and Apps with FME
A symptom-driven medical diagnosis support model based on machine learning te...
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Launch a Bumble-Style App with AI Features in 2025.pdf
Rapid Prototyping: A lecture on prototyping techniques for interface design
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
Build Real-Time ML Apps with Python, Feast & NoSQL
Co-training pseudo-labeling for text classification with support vector machi...
Human Computer Interaction Miterm Lesson
Decision Optimization - From Theory to Practice
How to Convert Tickets Into Sales Opportunity in Odoo 18
Lung cancer patients survival prediction using outlier detection and optimize...
Streamline Vulnerability Management From Minimal Images to SBOMs
CEH Module 2 Footprinting CEH V13, concepts
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
Identification of potential depression in social media posts

ZendCon 2017 - Build a Bot Workshop - Async Primer

  • 1. @adam_englander Build A Bot Workshop: Async Primer Adam Englander iovation
  • 2. @adam_englander What You Will Need • PHP 7.0, or 7.1 (Examples will be 7.1) • intl extension • Twitter account • Twitter Developer App: https://apps.twitter.com • OAuth Credentials: https://dev.twitter.com/oauth/ overview/application-owner-access-tokens
  • 3. @adam_englander What We Will Discuss • Concurrent Programming • Asynchronous I/O • AMPHP Asynchronous Framework for PHP
  • 4. @adam_englander What We Will Do 1. We will use an asynchronous HTTP client to execute a Twitter REST API command. 2. We will use an asynchronous HTTP client to process a continuous stream via the Twitter User Stream API. 3. We will leverage both of the above to listen to a topic and automatically respond to updates.
  • 5. @adam_englander Concurrent Programming • Forking and Threading • Asynchronous I/O • Fork/Join • Event Loop Strategies Methodologies
  • 6. @adam_englander Forking and Threading • Available in PHP core since PHP 4.1 • Requires the use of shared memory • Requires code to be written for management of forks/threads • Creates separate copies of code for each thread/fork
  • 7. @adam_englander Asynchronous I/O • Frees up the current process while I/O is performed • Executes code based on I/O events • No copying of code for separate process
  • 8. @adam_englander Asynchronous I/O Libraries • Streams via stream_select and socket_select • eio — libeio • ev — libev • libevent — libevent • event — libevent
  • 9. @adam_englander Fork/Thread vs Async I/O • Compute heavy • Process isolation • Non-Async library • I/O processes • Process/memory optimization Fork/Thread Async I/O
  • 10. @adam_englander Fork/Join Parallelism S TA RT P R O C E S S 1 P R O C E S S 2 P R O C E S S 3 E N DF O R K J O I N
  • 11. Fork/Join Example $dispatcher = new AmpThreadDispatcher();
 $a = $dispatcher->call('slowProcess1');
 $b = $dispatcher->call('slowProcess2');
 $c = $dispatcher->call('slowProcess3');
 
 $comboPromise = Ampall([$a, $b, $c]);
 list($a, $b, $c) = Ampwait($comboPromise);
  • 12. @adam_englander Event Loop Parallelism P R O C E S S Q U E U E I T E M Q U E U E I T E M I N Q U E U E ? X Yes No A S Y N C P R O C E S S A S Y N C P R O C E S S A S Y N C P R O C E S S A S Y N C P R O C E S S
  • 13. Event Loop Example <?php
 # Build objects to handle asynchronous interaction
 $loop = ReactEventLoopFactory::create();
 $dnsFactory = new ReactDnsResolverFactory();
 $dns = $dnsFactory->createCached('8.8.8.8', $loop);
 $factory = new ReactHttpClientFactory();
 $client = $factory->create($loop, $dns);
 $resp = array(); # Create callback for handling response
 $responseHandler = function ($response) use ($resp) {
 $response->on( 'data', function ($data) use ($resp) {
 $resp[] = $data;
 });
 }; # Queue up requests to send
 $request = $client->request('GET', 'http://www.timeapi.org/utc/now');
 $request->on('response', $responseHandler);
 $request->end();
 
 $request = $client->request('GET', 'http://www.timeapi.org/utc/now');
 $request->on('response', $responseHandler);
 $request->end();
 
 # Run the loop
 $loop->run();
  • 14. @adam_englander Fork/Join vs Event Loop • Enhance existing synchronous apps • Promises • Hack/HHVM • Non-HTTP apps • Full async apps • High volume apps Fork/Join Event Loop
  • 15. Callbacks vs. Generators $stream = yield $apiClient->request($request);
 while (null !== $message = yield $stream->read()) {
 print($message[‘user’][‘screen_name’].": “.$message[‘text']);
 } Callback Generator Aerysrouter()
 ->get("/", function (AerysRequest $req, AerysResponse $resp) {
 $resp->end("<h1>Hello World!</h1>");
 })
 ->head("/", function (AerysRequest $req, AerysResponse $resp) {
 $resp->end("<h1>Hello Head!</h1>");
 });
  • 17. @adam_englander Complete Modern Framework • Modular framework segmented into logical parts • Supersedes icicle.io • Drivers for common storage engines • Can be used for event loop and fork/join • Can use threads or async i/o
  • 19. @adam_englander • http://amphp.org/ • #amphp on Freenode IRC • http://blog.kelunik.com/ • https://dev.twitter.com/ • https://github.com/PeeHaa/AsyncTwitter • https://github.com/aenglander/amp-twitter-bot Resources