PHP Fibers & AMPHP testing with Phel
Testing concurrent programming with PHP 8.1+ Fibers and async libraries available via AMPHP by translating some of the examples to Phel code.
Related discussion in Phel repo where comments are welcome phel-lang/phel-lang#793.
Tested on:
- PHP 8.2.7 (Debian 12)
- Phel v0.16.1 (dev-main)
Repository is created from https://github.com/phel-lang/cli-skeleton/ template which has more in-depth info on how to run Phel.
composer install
vendor/bin/phel run src/helloworld.phel
# => Hello World from the future!%
vendor/bin/phel run src/socket/echo-server.phel
After startup, connect by running nc localhost 8888
, then type something to send message and see it echoed back.
vendor/bin/phel run src/socket/simple-http-server.phel
After startup, open http://127.0.0.1:8888 with web browser or: curl -vvv http://127.0.0.1:8888
More complete HTTP server example with routing, argument parsing, logging etc.
- https://github.com/amphp/http-server-router/blob/c0434ad6b1a0899f1fba5371e991974e77df1140/examples/hello-world.php
- https://amphp.org/http-server-router
vendor/bin/phel run src/http-server-router/hello-world.phel
Starts server at http://localhost:1337 (demo route with argument http://localhost:1337/myname ).
- Does not work in Phel REPL as stdout logger makes it exit.
- How are webservers with Clojure(Script) set up to work with REPL that allow redefining functions or live reloading on the fly?
- Research notes at phel-lang/phel-lang#794
- Something about AMPHP HTTP server cluster hotreloading: https://amphp.org/cluster#hot-reload-in-intellij--phpstorm
Example with server-sent event stream connection (SSE). Client keeps half-duplex HTTP connection open to server which pushes updates to client.
vendor/bin/phel run src/http-server/event-source.phel
- Open in browser: http://0.0.0.0:1337/
- https://github.com/amphp/sync?tab=readme-ov-file#channels How to represent such code with Phel?
[$left, $right] = createChannelPair();
$future1 = async(function () use ($left): void {
echo "Coroutine 1 started\n";
delay(1); // Delay to simulate I/O.
$left->send(42);
$received = $left->receive();
echo "Received ", $received, " in coroutine 1\n";
});
- https://github.com/amphp/sync?tab=readme-ov-file#approach-4-concurrentiterator
- https://github.com/amphp/pipeline
Original template repo readme continues...