In general, asynchronous (pronounced ay-SIHN-kro-nuhs, from Greek asyn-, meaning "not with," and chronos, meaning "time") is an adjective describing objects or events that are not coordinated in time.
Asynchronous means that a process operates independently of other processes.
No, PHP is synchronous
Process runs only as a result of some other process being completed or handing off operation.
console.log('Test 1');
setTimeout(function() {
console.log('Test 2');
}, 1);
console.log('Test 3');
function test1(){ echo 'Test 1' . PHP_EOL;}
function test2(){
sleep(3);
echo 'Test 2' . PHP_EOL;
}
function test3(){ echo 'Test 3' . PHP_EOL;}
test1();
test2();
test3();
JS
PHP
JS
PHP
Test 1
Test 2
Test 3
Test 1
Test 3
Test 2
We are not talking about the JavaScript library
It is not a tool that is used to make working with React and PHP easier
It's not a framework
ReactPHP is not a framework.
It's a set of independent components which means you take the parts you need.
$ composer require react/react
Three Core Components:
Steps:
Register Event
Listen
Get notified so you can react to event
Install
Usage
$ composer require react/event-loop
$loop = React\EventLoop\Factory::create();
$loop->addPeriodicTimer(1, function () {
echo "Test\n";
});
$loop->run();
Example
require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
echo "Test 1\n";
$loop->addTimer(3, function(){
echo "Test 2\n";
});
echo "Test 3\n";
$loop->run();
Other Methods
Allow you to process data in pieces
3 Types:
require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$stream = new \React\Stream\ReadableResourceStream(STDIN, $loop);
$stream->on('data', function($data){
// process data *line by line*
});
$stream->on('end', function(){
echo "finished\n";
});
$loop->run();
require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$writable = new \React\Stream\WriteableResourceStream(STDOUT, $loop);
$writable->write('Test');
$loop->run();
Represents the eventual completion (or failure) of an asynchronous operation, and its resulting value
3 States:
$deferred = new React\Promise\Deferred();
$promise = $deferred->promise();
$promise->then(
function($data){
//run code
},
function($data){
//run code
});
$deferred->reject('hello world');
require 'vendor/autoload.php';
function testPromise($url, $method)
{
$deferred = new React\Promise\Deferred();
$response = true;
if ($response){
$deferred->resolve($response);
} else {
$deferred->reject(new Exception('Failed'));
}
return $deferred->promise();
}
testPromise("http://eddie.com", "GET")->then(
// fullfilled
function($response){
echo $response . PHP_EOL;
},
// rejected
function(Exception $exception){
echo $exception->getMessage() . PHP_EOL;
}
);
Other methods
More Components