SlideShare a Scribd company logo
1 of 45
Download to read offline
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 ļ¬‚ow of the application is determined by events.

This might be user interaction, ļ¬le reads, ļ¬le 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 ļ¬le,
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 ļ¬les or network
endpoints (and more) without blocking
Streams
ā€¢ Let's say you had a log ļ¬le that was 2gb in size.

ā€¢ You could load that into memory using ļ¬le() 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 ļ¬le.

ā€¢ You can then read through the contents of the ļ¬le 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 diļ¬€erent types of
resources

ā€¢ We have already seen the ļ¬le:// wrapper in use through
the ļ¬le() 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 ļ¬le in memory. You
can then write to and read from that ļ¬le.ā€Ø
// 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 deļ¬ned and assigned to
variables.

ā€¢ You might have heard these being called closures or
lambda functions or anonymous functions.

ā€¢ There is a little diļ¬€erence 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 ļ¬le.

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 ļ¬le 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 ļ¬ne. 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 ļ¬‚ow is "request > action > response" but
that no longer applies here.

ā€¢ 'non-blocking' means you can't access ļ¬les, 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
ā€¢ Oļ¬ƒcial 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.5Tom Corrigan
Ā 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
Ā 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
Ā 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationWorkhorse Computing
Ā 
An Introduction to Symfony
An Introduction to SymfonyAn Introduction to Symfony
An Introduction to Symfonyxopn
Ā 
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
Ā 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with phpElizabeth Smith
Ā 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond PhoenixGabriele 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 patternsit-people
Ā 
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 applicationrjsmelo
Ā 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rackdanwrong
Ā 
関č„æ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

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 PrimerAdam Englander
Ā 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challengervanphp
Ā 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop NotesPamela Fox
Ā 
PHP and COM
PHP and COMPHP and COM
PHP and COMWez Furlong
Ā 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
Ā 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
Ā 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principlesPerl Careers
Ā 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
Ā 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpointwebhostingguy
Ā 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generatorsdantleech
Ā 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basicsAbhay Sapru
Ā 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting BasicsDr.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 jQueryTatsuhiko 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 easeOscar 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 2016Codemotion
Ā 
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 ConfigurationPhilip Norton
Ā 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionPhilip Norton
Ā 
Drupal 8 Services
Drupal 8 ServicesDrupal 8 Services
Drupal 8 ServicesPhilip Norton
Ā 
Webform and Drupal 8
Webform and Drupal 8Webform and Drupal 8
Webform and Drupal 8Philip Norton
Ā 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal CertificationPhilip Norton
Ā 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master BuilderPhilip Norton
Ā 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthPhilip Norton
Ā 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration ManagementPhilip Norton
Ā 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalPhilip Norton
Ā 
Drupal theming
Drupal themingDrupal theming
Drupal themingPhilip Norton
Ā 
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 SwallowPhilip Norton
Ā 
Drupal 7 Queues
Drupal 7 QueuesDrupal 7 Queues
Drupal 7 QueuesPhilip 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

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
Ā 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
Ā 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
Ā 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
Ā 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
Ā 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
Ā 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
Ā 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
Ā 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
Ā 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
Ā 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
Ā 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
Ā 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
Ā 

Recently uploaded (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Ā 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
Ā 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Ā 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Ā 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Ā 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
Ā 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
Ā 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
Ā 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Ā 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
Ā 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
Ā 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
Ā 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
Ā 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
Ā 

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 ļ¬‚ow of the application is determined by events. This might be user interaction, ļ¬le reads, ļ¬le 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 ļ¬le, 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 ļ¬les or network endpoints (and more) without blocking
  • 15. Streams ā€¢ Let's say you had a log ļ¬le that was 2gb in size. ā€¢ You could load that into memory using ļ¬le() 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 ļ¬le. ā€¢ You can then read through the contents of the ļ¬le 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 diļ¬€erent types of resources ā€¢ We have already seen the ļ¬le:// wrapper in use through the ļ¬le() 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 ļ¬le in memory. You can then write to and read from that ļ¬le.ā€Ø // 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 deļ¬ned and assigned to variables. ā€¢ You might have heard these being called closures or lambda functions or anonymous functions. ā€¢ There is a little diļ¬€erence 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 ļ¬le. 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 ļ¬le 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 ļ¬ne. 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 ļ¬‚ow is "request > action > response" but that no longer applies here. ā€¢ 'non-blocking' means you can't access ļ¬les, 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 ā€¢ Oļ¬ƒcial 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