SlideShare a Scribd company logo
ReactPHP
Phil Norton
Phil Norton
Help run NWDUG
Blog at #! code (www.hashbangcode.com)
@philipnorton42 on Twitter
“Event-driven, non-blocking I/O with PHP”
Event-driven, non-blocking I/O with PHP
The flow of the application is determined by events.

This might be user interaction, file reads, file writes,
network events, etc.

Even errors will trigger an event.
Event-driven, non-blocking I/O with PHP
The program runs without causing any blocking of
CPU runtime.

This is usually things like reading or writing to a file,
communicating with a network resource.

The idea is that any pure CPU interaction will be
many times faster than network requests.

In basic terms, a call to sleep() will block the program
from running.
Event-driven, non-blocking I/O with PHP
As in Input/Output.

Meaning that we are dealing with the input and
output of data.

In ReactPHP this is done via streams to prevent
blocking.

Streams can be read from or written to in a linear
fashion and don't need to be consumed in full.
Event-driven, non-blocking I/O with PHP
The system is written in pure PHP.

i.e. no third part libraries or other packages are
needed to run ReactPHP.
ReactPHP
• Forget the normal request > action > response
mechanisms that you are familiar with.

• ReactPHP acts around a central loop and acts more like a
desktop application than a web application.
ReactPHP
ReactPHP is good for:

• Servers

• Clients

• Long-running processes
Creating servers?
This is a fully working HTTP server, written using ReactPHP.

<?php
$loop = ReactEventLoopFactory::create();

$server = stream_socket_server('tcp://127.0.0.1:8080');
stream_set_blocking($server, false);
$loop->addReadStream($server, function ($server) use ($loop) {
$conn = stream_socket_accept($server);
$data = "HTTP/1.1 200 OKrnContent-Length: 3rnrnHin";
$loop->addWriteStream($conn, function ($conn) use (&$data, $loop) {
$written = fwrite($conn, $data);
if ($written === strlen($data)) {
fclose($conn);

$loop->removeWriteStream($conn);
} else {

$data = substr($data, $written);
}

});
});

$loop->run();
Install Via Composer
• Include ReactPHP in your composer based project

composer require react/react
• Once you've included /vendor/autoload.php you should
be ready to go.

require './vendor/autoload.php';
ReactPHP
ReactPHP heavily uses the following aspects of PHP

• Streams

• Closures

It makes sense to understand what these are.

So let's have a quick look at them.
Streams
Streams
• Available since PHP 4.3.0

• Mostly used transparently in PHP

• Can be used explicitly

• Allows you to read and write from files or network
endpoints (and more) without blocking
Streams
• Let's say you had a log file that was 2gb in size.

• You could load that into memory using file() and the read
the contents.

$contents = file('logfile.log');
• This would quickly overload your system resources.
Streams
• A better approach is to use streams to open a stream to
the file.

• You can then read through the contents of the file without
overloading the system resources.

$handle = fopen('logfile.log', 'r');
while (false !== ($line = fgets($handle))) {
// Do something.
}
• The fopen() function creates a stream, fgets() reads data
from the stream.
Stream Wrappers
• A few stream wrappers are built into PHP

• This allows access to data held in different types of
resources

• We have already seen the file:// wrapper in use through
the file() function (although you can't use it explicitly).
php://input
php://input will read from input.

The following will print out any data sent to the script. Eg
post request data.

$input = fopen('php://input', 'r');

while (false !== ($line = fgets($input))) {
echo $line;
}
php://memory
php://memory will create a temporary file in memory. You
can then write to and read from that file.

// Open memory stream for reading and writing.
$memoryStream = fopen('php://memory', 'rw+');


// Write to the stream.
$text = 'sometext' . time();
fwrite($memoryStream, $text);

http:// & https://
http:// and https:// are standard stream wrappers that allow
streaming of a web resource

// Open stream to awesome website.

$stream = fopen('https://www.hashbangcode.com/', 'r');
// Read the first 50 bytes.
echo fread($stream, 50);
Streams
Remember:

Not a stream

$string = file_get_contents('file.txt');
A stream

$stream = fopen('file.txt', 'r');
Streams
Read more:

PHP Streams:

https://www.hashbangcode.com/article/php-streams

PHP Stream Wrappers

https://www.hashbangcode.com/article/php-custom-stream-wrappers
Closures
Closures
• Since PHP 5.3 functions can be generated at runtime

• This means that functions can be defined and assigned to
variables.

• You might have heard these being called closures or
lambda functions or anonymous functions.

• There is a little difference between them though.
Lambda Functions
Lambda functions are essentially anonymous closures that
have no knowledge of their environment.

usort($array, function ($a, $b) {
return $a->property <=> $b->property;
});
This function will not exist outside of the call to usort() and
will be deleted from memory after completion.
Lambda Functions
Lambdas can also be assigned to variables.

$closure = function ($name) {
return 'Hello ' . $name . '!';
};
This can now be used anywhere within the same scope.



echo $closure('Phil');
// prints "Hello Phil!
Closures
Closures inherit variables from the parent context via the use
statement.

$day = 'Wednesday';
$closure = function ($name) use ($day) {
return 'Hello ' . $name . '! It is ' . $day . ' today.';
};
echo $closure('Phil');
// Prints "Hello Phil! It is Wednesday."
Closures
In reality, the terms lambda and closures are often used
interchangeably.

Many languages swap their names around.

So, don’t worry about the name.
The Loop
The Loop
• Everything in ReactPHP is centred around an event loop

// Set up the loop.
$loop = ReactEventLoopFactory::create();

// some code that uses the instance 

// of the loop event


// Run the loop.
$loop->run();
Periodic Timer
• The simplest example of the loop in action is with a
periodic timer.

$loop = ReactEventLoopFactory::create();

$counter = 0;

$loop->addPeriodicTimer(1, function() use (&$counter) {
$counter++;

echo "$countern";

});


$loop->run();
• This will count up from 0, every second, forever.
Read File
• Another example is to read a file.

use ReactStreamReadableResourceStream;



$loop = ReactEventLoopFactory::create();


$stream = new ReadableResourceStream(fopen('file.txt', 'r'), $loop);
$stream->on('data', function ($data) {
echo "Read" . $data . PHP_EOL;
});

$stream->on('end', function () {
echo "Finished" . PHP_EOL;

});

$loop->run();
• This will read a file in, print each line and then print, "Finished" when complete.
Create A Chat
Application In React
Chat
• A chat application is a pool of connections (i.e. users) and
a communication stream between them all.

• When a user enters some text this should be copied to all
other connections in the pool.
ConnectionsPool
class ConnectionsPool {

private $connections;
public function __construct() {

$this->connections = new SplObjectStorage();

}


public function add(ConnectionInterface $connection) {
$connection->write("Welcome to chatn");


$this->initEvents($connection);

$this->connections->attach($connection);

$this->sendAll("New user enters the chatn", $connection);
echo $this->connections->count() . ' users connected.' . PHP_EOL;
}
}
ConnectionsPool
private function initEvents(ConnectionInterface $connection) {
// On receiving the data we loop through other connections
// from the pool and write this data to them
$connection->on('data', function ($data) use ($connection) {

$this->sendAll($data, $connection);

});
// When connection closes detach it from the pool.
$connection->on('close', function () use ($connection) {

$this->connections->detach($connection);

$this->sendAll("A user leaves the chatn", $connection);

echo $this->connections->count() . ' users connected.' .
PHP_EOL;
});
}
ConnectionsPool
private function sendAll($data, ConnectionInterface $except){

foreach ($this->connections as $conn) {

if ($conn == $except) {

continue;

}


$conn->write($data);

}

}
ReactPHP
use ReactSocketServer;
$loop = ReactEventLoopFactory::create();

$socket = new Server('0.0.0.0:8080', $loop);
$pool = new ConnectionsPool();
$socket->on('connection', 

function (ConnectionInterface $connection) use ($pool) {
$pool->add($connection);
});

echo "Listening on ". $socket->getAddress() . PHP_EOL;

$loop->run();
Run the chat server
$ php chat.php
Listening on tcp://0.0.0.0:8080
Connect to chat
nc <ip address> 8080
telnet <ip address> 8080
Connect to chat
• Connecting to the chat server using telnet is fine. But it’s
also possible to create a chat client using ReactPHP.
Conclusion
• ReactPHP takes a bit of getting your head around.

• PHP's normal flow is "request > action > response" but
that no longer applies here.

• 'non-blocking' means you can't access files, databases
or anything like that without going through a streams.

• Thankfully a few ReactPHP libraries exist to wrap those
resources and turn them into streams.
Resources
• Official Website : https://reactphp.org/

• List of third party libraries using ReactPHP: 

https://github.com/reactphp/reactphp/wiki/Users

• Book: Event Driven PHP With React PHP - Sergey Zhuk
Thanks!
Help run NWDUG
Blog at #! code (www.hashbangcode.com)
@philipnorton42 on Twitter
Phil Norton

More Related Content

What's hot

Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
Workhorse Computing
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
Dave Cross
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
Workhorse Computing
 
An Introduction to Symfony
An Introduction to SymfonyAn Introduction to Symfony
An Introduction to Symfony
xopn
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
Workhorse Computing
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
Workhorse Computing
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
Elizabeth Smith
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
Gabriele Lana
 
Symfony internals [english]
Symfony internals [english]Symfony internals [english]
Symfony internals [english]
Raul Fraile
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
Workhorse Computing
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Sf2 wtf
Sf2 wtfSf2 wtf
Findbin libs
Findbin libsFindbin libs
Findbin libs
Workhorse Computing
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
rjsmelo
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
danwrong
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.
Workhorse Computing
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Puppet
 

What's hot (20)

Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 
An Introduction to Symfony
An Introduction to SymfonyAn Introduction to Symfony
An Introduction to Symfony
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
 
Symfony internals [english]
Symfony internals [english]Symfony internals [english]
Symfony internals [english]
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Sf2 wtf
Sf2 wtfSf2 wtf
Sf2 wtf
 
Findbin libs
Findbin libsFindbin libs
Findbin libs
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 

Similar to ReactPHP

Php hacku
Php hackuPhp hacku
ZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async PrimerZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challenger
vanphp
 
Php mysql ppt
Php mysql pptPhp mysql ppt
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
PHP and COM
PHP and COMPHP and COM
PHP and COM
Wez Furlong
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
Wim Godden
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
Perl Careers
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
Rob Tweed
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
Tom Praison Praison
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
dantleech
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
Abhay Sapru
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
Symfony console: build awesome command line scripts with ease
Symfony console: build awesome command line scripts with easeSymfony console: build awesome command line scripts with ease
Symfony console: build awesome command line scripts with ease
Oscar Merida
 
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
Codemotion
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
Zend by Rogue Wave Software
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.
Binny V A
 

Similar to ReactPHP (20)

Php hacku
Php hackuPhp hacku
Php hacku
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async PrimerZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async Primer
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challenger
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
PHP and COM
PHP and COMPHP and COM
PHP and COM
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Symfony console: build awesome command line scripts with ease
Symfony console: build awesome command line scripts with easeSymfony console: build awesome command line scripts with ease
Symfony console: build awesome command line scripts with ease
 
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.
 

More from Philip Norton

Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 Configuration
Philip Norton
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
Philip Norton
 
Drupal 8 Services
Drupal 8 ServicesDrupal 8 Services
Drupal 8 Services
Philip Norton
 
Webform and Drupal 8
Webform and Drupal 8Webform and Drupal 8
Webform and Drupal 8
Philip Norton
 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal Certification
Philip Norton
 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master Builder
Philip Norton
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
Philip Norton
 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration Management
Philip Norton
 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And Drupal
Philip Norton
 
Drupal theming
Drupal themingDrupal theming
Drupal theming
Philip Norton
 
Drush
DrushDrush
Making The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To SwallowMaking The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To Swallow
Philip Norton
 
Drupal 7 Queues
Drupal 7 QueuesDrupal 7 Queues
Drupal 7 Queues
Philip Norton
 

More from Philip Norton (13)

Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 Configuration
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Drupal 8 Services
Drupal 8 ServicesDrupal 8 Services
Drupal 8 Services
 
Webform and Drupal 8
Webform and Drupal 8Webform and Drupal 8
Webform and Drupal 8
 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal Certification
 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master Builder
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration Management
 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And Drupal
 
Drupal theming
Drupal themingDrupal theming
Drupal theming
 
Drush
DrushDrush
Drush
 
Making The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To SwallowMaking The Drupal Pill Easier To Swallow
Making The Drupal Pill Easier To Swallow
 
Drupal 7 Queues
Drupal 7 QueuesDrupal 7 Queues
Drupal 7 Queues
 

Recently uploaded

Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
FODUU
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 

Recently uploaded (20)

Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 

ReactPHP

  • 2. Phil Norton Help run NWDUG Blog at #! code (www.hashbangcode.com) @philipnorton42 on Twitter
  • 4. Event-driven, non-blocking I/O with PHP The flow of the application is determined by events. This might be user interaction, file reads, file writes, network events, etc. Even errors will trigger an event.
  • 5. Event-driven, non-blocking I/O with PHP The program runs without causing any blocking of CPU runtime. This is usually things like reading or writing to a file, communicating with a network resource. The idea is that any pure CPU interaction will be many times faster than network requests. In basic terms, a call to sleep() will block the program from running.
  • 6. Event-driven, non-blocking I/O with PHP As in Input/Output. Meaning that we are dealing with the input and output of data. In ReactPHP this is done via streams to prevent blocking. Streams can be read from or written to in a linear fashion and don't need to be consumed in full.
  • 7. Event-driven, non-blocking I/O with PHP The system is written in pure PHP. i.e. no third part libraries or other packages are needed to run ReactPHP.
  • 8. ReactPHP • Forget the normal request > action > response mechanisms that you are familiar with. • ReactPHP acts around a central loop and acts more like a desktop application than a web application.
  • 9. ReactPHP ReactPHP is good for: • Servers • Clients • Long-running processes
  • 10. Creating servers? This is a fully working HTTP server, written using ReactPHP. <?php $loop = ReactEventLoopFactory::create();
 $server = stream_socket_server('tcp://127.0.0.1:8080'); stream_set_blocking($server, false); $loop->addReadStream($server, function ($server) use ($loop) { $conn = stream_socket_accept($server); $data = "HTTP/1.1 200 OKrnContent-Length: 3rnrnHin"; $loop->addWriteStream($conn, function ($conn) use (&$data, $loop) { $written = fwrite($conn, $data); if ($written === strlen($data)) { fclose($conn);
 $loop->removeWriteStream($conn); } else {
 $data = substr($data, $written); }
 }); });
 $loop->run();
  • 11. Install Via Composer • Include ReactPHP in your composer based project composer require react/react • Once you've included /vendor/autoload.php you should be ready to go. require './vendor/autoload.php';
  • 12. ReactPHP ReactPHP heavily uses the following aspects of PHP • Streams • Closures It makes sense to understand what these are. So let's have a quick look at them.
  • 14. Streams • Available since PHP 4.3.0 • Mostly used transparently in PHP • Can be used explicitly • Allows you to read and write from files or network endpoints (and more) without blocking
  • 15. Streams • Let's say you had a log file that was 2gb in size. • You could load that into memory using file() and the read the contents.
 $contents = file('logfile.log'); • This would quickly overload your system resources.
  • 16. Streams • A better approach is to use streams to open a stream to the file. • You can then read through the contents of the file without overloading the system resources. $handle = fopen('logfile.log', 'r'); while (false !== ($line = fgets($handle))) { // Do something. } • The fopen() function creates a stream, fgets() reads data from the stream.
  • 17. Stream Wrappers • A few stream wrappers are built into PHP • This allows access to data held in different types of resources • We have already seen the file:// wrapper in use through the file() function (although you can't use it explicitly).
  • 18. php://input php://input will read from input. The following will print out any data sent to the script. Eg post request data. $input = fopen('php://input', 'r');
 while (false !== ($line = fgets($input))) { echo $line; }
  • 19. php://memory php://memory will create a temporary file in memory. You can then write to and read from that file.
 // Open memory stream for reading and writing. $memoryStream = fopen('php://memory', 'rw+'); 
 // Write to the stream. $text = 'sometext' . time(); fwrite($memoryStream, $text);

  • 20. http:// & https:// http:// and https:// are standard stream wrappers that allow streaming of a web resource
 // Open stream to awesome website.
 $stream = fopen('https://www.hashbangcode.com/', 'r'); // Read the first 50 bytes. echo fread($stream, 50);
  • 21. Streams Remember: Not a stream $string = file_get_contents('file.txt'); A stream $stream = fopen('file.txt', 'r');
  • 22. Streams Read more: PHP Streams: https://www.hashbangcode.com/article/php-streams PHP Stream Wrappers https://www.hashbangcode.com/article/php-custom-stream-wrappers
  • 24. Closures • Since PHP 5.3 functions can be generated at runtime • This means that functions can be defined and assigned to variables. • You might have heard these being called closures or lambda functions or anonymous functions. • There is a little difference between them though.
  • 25. Lambda Functions Lambda functions are essentially anonymous closures that have no knowledge of their environment.
 usort($array, function ($a, $b) { return $a->property <=> $b->property; }); This function will not exist outside of the call to usort() and will be deleted from memory after completion.
  • 26. Lambda Functions Lambdas can also be assigned to variables.
 $closure = function ($name) { return 'Hello ' . $name . '!'; }; This can now be used anywhere within the same scope. 
 echo $closure('Phil'); // prints "Hello Phil!
  • 27. Closures Closures inherit variables from the parent context via the use statement.
 $day = 'Wednesday'; $closure = function ($name) use ($day) { return 'Hello ' . $name . '! It is ' . $day . ' today.'; }; echo $closure('Phil'); // Prints "Hello Phil! It is Wednesday."
  • 28. Closures In reality, the terms lambda and closures are often used interchangeably. Many languages swap their names around. So, don’t worry about the name.
  • 30. The Loop • Everything in ReactPHP is centred around an event loop // Set up the loop. $loop = ReactEventLoopFactory::create();
 // some code that uses the instance 
 // of the loop event 
 // Run the loop. $loop->run();
  • 31. Periodic Timer • The simplest example of the loop in action is with a periodic timer. $loop = ReactEventLoopFactory::create();
 $counter = 0;
 $loop->addPeriodicTimer(1, function() use (&$counter) { $counter++;
 echo "$countern";
 }); 
 $loop->run(); • This will count up from 0, every second, forever.
  • 32. Read File • Another example is to read a file. use ReactStreamReadableResourceStream;
 
 $loop = ReactEventLoopFactory::create(); 
 $stream = new ReadableResourceStream(fopen('file.txt', 'r'), $loop); $stream->on('data', function ($data) { echo "Read" . $data . PHP_EOL; });
 $stream->on('end', function () { echo "Finished" . PHP_EOL;
 });
 $loop->run(); • This will read a file in, print each line and then print, "Finished" when complete.
  • 34. Chat • A chat application is a pool of connections (i.e. users) and a communication stream between them all. • When a user enters some text this should be copied to all other connections in the pool.
  • 35. ConnectionsPool class ConnectionsPool {
 private $connections; public function __construct() {
 $this->connections = new SplObjectStorage();
 } 
 public function add(ConnectionInterface $connection) { $connection->write("Welcome to chatn"); 
 $this->initEvents($connection);
 $this->connections->attach($connection);
 $this->sendAll("New user enters the chatn", $connection); echo $this->connections->count() . ' users connected.' . PHP_EOL; } }
  • 36. ConnectionsPool private function initEvents(ConnectionInterface $connection) { // On receiving the data we loop through other connections // from the pool and write this data to them $connection->on('data', function ($data) use ($connection) {
 $this->sendAll($data, $connection);
 }); // When connection closes detach it from the pool. $connection->on('close', function () use ($connection) {
 $this->connections->detach($connection);
 $this->sendAll("A user leaves the chatn", $connection);
 echo $this->connections->count() . ' users connected.' . PHP_EOL; }); }
  • 37. ConnectionsPool private function sendAll($data, ConnectionInterface $except){
 foreach ($this->connections as $conn) {
 if ($conn == $except) {
 continue;
 } 
 $conn->write($data);
 }
 }
  • 38. ReactPHP use ReactSocketServer; $loop = ReactEventLoopFactory::create();
 $socket = new Server('0.0.0.0:8080', $loop); $pool = new ConnectionsPool(); $socket->on('connection', 
 function (ConnectionInterface $connection) use ($pool) { $pool->add($connection); });
 echo "Listening on ". $socket->getAddress() . PHP_EOL;
 $loop->run();
  • 39. Run the chat server $ php chat.php Listening on tcp://0.0.0.0:8080
  • 40. Connect to chat nc <ip address> 8080 telnet <ip address> 8080
  • 41. Connect to chat • Connecting to the chat server using telnet is fine. But it’s also possible to create a chat client using ReactPHP.
  • 42. Conclusion • ReactPHP takes a bit of getting your head around. • PHP's normal flow is "request > action > response" but that no longer applies here. • 'non-blocking' means you can't access files, databases or anything like that without going through a streams. • Thankfully a few ReactPHP libraries exist to wrap those resources and turn them into streams.
  • 43. Resources • Official Website : https://reactphp.org/ • List of third party libraries using ReactPHP: 
 https://github.com/reactphp/reactphp/wiki/Users • Book: Event Driven PHP With React PHP - Sergey Zhuk
  • 45. Help run NWDUG Blog at #! code (www.hashbangcode.com) @philipnorton42 on Twitter Phil Norton