PHP implementation of tj/co

dev-master 2017-06-27 13:15 UTC

This package is not auto-updated.

Last update: 2023-09-30 12:47:04 UTC


PHP implementation of tj/co. Uses generator functions and co-routines (php>=5.5.0) to handle asynchronicity in an apparently synchronous manner.


composer require netgusto/co




use React\EventLoop\Factory as EventLoopFactory,
    React\Socket\Server as SocketServer,
    React\Http\Server as HttpServer;

$loop = EventLoopFactory::create();
$socket = new SocketServer($loop);
$http = new HttpServer($socket);

// we hook co to the reactphp eventloop

function someAsynchronousAPI() {
    return Promise(function($resolve) {
        setTimeout(function() use(&$resolve) {
            // asynchronously resolved after 10ms; could be anything async !
            $resolve(['one', 'two', 'three', rand()]);
        }, 10);

$gen = function() {
    $data = (yield someAsynchronousAPI());

    # php has suspended on "yield"
    # until the promise returned by someAsynchronousAPI() was resolved.
    # Starting from here, we can use $data synchronously !

    yield ['message' => 'Hello World from co !', 'asyncdata' => $data];

$http->on('request', function($req, $res) use (&$gen) {
    co::run($gen)->then(function($value) use(&$req, &$res) {
        $res->writeHead(200, ['Content-Type' => 'application/json']);

echo "Magic happens on http://localhost:3000\n";