Icicle is a PHP library for writing asynchronous code using synchronous coding techniques
MIT License
Icicle is now deprecated in favor of Amp v2.0. This version is is currently under development, but close to release. The v2.0 branches are amp_v2 in all packages except the main Amp package, loop package, and postgres package, where v2.0 is the master branch.
Icicle is a PHP library for writing asynchronous code using synchronous coding techniques.
Icicle uses Coroutines built with Awaitables and Generators to facilitate writing asynchronous code using techniques normally used to write synchronous code, such as returning values and throwing exceptions, instead of using nested callbacks typically found in asynchronous code.
The recommended way to install Icicle is with the Composer package manager. (See the Composer installation guide for information on installing and using Composer.)
Run the following command to use Icicle in your project:
composer require icicleio/icicle
You can also manually edit composer.json
to add Icicle as a project requirement.
// composer.json
{
"require": {
"icicleio/icicle": "^0.9"
}
}
The example script below demonstrates how awaitables can be yielded in a coroutine to create interruption points. Fulfillment values of awaitables are sent to the coroutine and rejection exceptions are thrown into the coroutine.
#!/usr/bin/env php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Awaitable;
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
$generator = function () {
try {
// Sets $start to the value returned by microtime() after approx. 1 second.
$start = (yield Awaitable\resolve(microtime(true))->delay(1));
echo "Sleep time: ", microtime(true) - $start, "\n";
// Throws the exception from the rejected promise into the coroutine.
yield Awaitable\reject(new Exception('Rejected promise'));
} catch (Exception $e) { // Catches promise rejection reason.
echo "Caught exception: ", $e->getMessage(), "\n";
}
yield Awaitable\resolve('Coroutine completed');
};
$coroutine = new Coroutine($generator());
$coroutine->done(function ($data) {
echo $data, "\n";
});
Loop\run();