An asynchronous PHP framework with and event loop (node.js-like)

v0.0.4 2012-11-01 13:45 UTC



An asynchronous PHP framework with an event loop (node.js-like)

The preferred way is to use composer.

  "require": { "iankuca/node": "*" }

Or just use this repository directly.


$ php -f main.php yourfile.php



echo "A";
setTimeout(function () {
  echo "C";
}, 2000);
echo "B";

This prints AB and adds C after 2 seconds. Then it exits.

HTTP Server

$server = \Node\HTTP::createServer(function ($req, $res) {
  $res->writeHead(200, array(
    'content-type' => 'text/plain; charset=UTF-8'
  $res->write('Hello world!');

$port = 8080;
$server->listen($port, 'localhost');
console_log('The HTTP server is listening on port %d.', $port);

This creates an HTTP server listening on the port 8080. It writes Hello world! to each response. It does not exit by itself.

HTTP Request

$options = array(
  'host' => 'ifconfig.me',
  'path' => '/ip'

\Node\HTTP::request($options, function ($res) {
  console_log('status: %d', $res->status);

  $res->on('data', function ($chunk) {
    echo $chunk;

This makes an HTTP GET request to http://ifoconfig.me/ip and asynchronously calls the provided callback function when a response object is ready. If waits for response body. Then it exits.

The standard output would be…

status: 200

Directory Listing

\Node\FS::readdir('/tmp', function ($err, $files) {
  if ($err) throw $err;

Spawns a child ls -a /tmp process and asynchronously calls the provided callback function when done. Then it exits.


Since the standard output of the process does not go to the browser, eventual exceptions and warnings are visible in the terminal window. The native exception stringifier is pretty horrible which is why node.php includes its own error formatter. Exceptions are now a lot nicer:

Exception Example

Another addition is the console_log() function which is basically sprintf that outputs to the standard output with an added end-of-line (\n) character.

console_log('%d + %d = %s', 1, 2, 'awesome');
// stdout: 1 + 2 = awesome