php-tokio/examples/reqwest
2023-08-29 20:50:06 +02:00
..
.cargo Add example 2023-08-27 19:32:52 +02:00
lib Add cs rules 2023-08-29 15:28:35 +02:00
src Run cargo fmt 2023-08-29 20:50:06 +02:00
.gitignore Add cs rules 2023-08-29 15:28:35 +02:00
.php-cs-fixer.dist.php Add cs rules 2023-08-29 15:28:35 +02:00
Cargo.toml Update example 2023-08-27 20:25:28 +02:00
composer.json Add cs rules 2023-08-29 15:28:35 +02:00
README.md Improve examples 2023-08-27 20:40:41 +02:00
test.php Add cs rules 2023-08-29 15:28:35 +02:00

php-tokio example

Here's a usage example of php-tokio, using the async Rust reqwest library to make asynchronous HTTP requests from PHP:

<?php

use Reqwest\Client;

use function Amp\async;
use function Amp\Future\await;

require 'vendor/autoload.php';

Client::init();

function test(int $delay): void {
    $url = "https://httpbin.org/delay/$delay";
    $t = time();
    echo "Making async reqwest to $url that will return after $delay seconds...".PHP_EOL;
    Client::get($url);
    $t = time() - $t;
    echo "Got response from $url after ~".$t." seconds!".PHP_EOL;
};

$futures = [];
$futures []= async(test(...), 5);
$futures []= async(test(...), 5);
$futures []= async(test(...), 5);

await($futures);

Usage:

cd examples/reqwest && \
    cargo build && \
    composer update && \
    php -d extension=../../target/debug/libexample_reqwest.so test.php

Result:

Making async reqwest to https://httpbin.org/delay/5 that will return after 5 seconds...
Making async reqwest to https://httpbin.org/delay/5 that will return after 5 seconds...
Making async reqwest to https://httpbin.org/delay/5 that will return after 5 seconds...
Got response from https://httpbin.org/delay/5 after ~5 seconds!
Got response from https://httpbin.org/delay/5 after ~5 seconds!
Got response from https://httpbin.org/delay/5 after ~5 seconds!

See the source code of the example for more info on how it works!