2017 © Pedro Peláez
 

library co

PHP implementation of tj/co

image

netgusto/co

PHP implementation of tj/co

  • Tuesday, June 27, 2017
  • by netgusto
  • Repository
  • 1 Watchers
  • 2 Stars
  • 3 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

co

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

Install

composer require netgusto/co

Example

<?php

require('vendor/autoload.php');

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
co::setLoop($loop);

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']);
        $res->end(json_encode($value));
    });
});

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

$socket->listen(3000);
$loop->run();

The Versions

27/06 2017

dev-master

9999999-dev

PHP implementation of tj/co

  Sources   Download

MIT

The Requires

 

by Jérôme Schneider / Net Gusto

asynchronous async react reactphp coroutine