John Esposito edits Refcardz at DZone, while writing a dissertation on ancient Greek philosophy and raising two cats. In a previous life he was a database developer and network administrator. John is a DZone Zone Leader and has posted 320 posts at DZone. You can read more from them at their website. View Full User Profile

Node.js and PHP together: DNode in PHP

10.31.2011
| 26566 views |
  • submit to reddit

PHP is great because everybody uses it (and it's fast, and easy to learn, etc.). Node.js is great for lots of reasons, unless it isn't (and if controversy excites you, also see 1,2).

Henri Bergius doesn't want to choose between PHP and Node.js:

Both environments have their strong points. Node.js is very fast and flexible, but PHP has a lot more mature tools and libraries available. So in a lot of projects it is hard to choose between the two. But now you might not have to.

..and now, thanks to his implementation of DNode in PHP, you can have your PHP cake and Node.js it too.

For example, if you create a DNode service for Node.js like this:

var dnode = require('dnode');
var server = dnode({
    zing: function (n, cb) { cb(n * 100) }
});
server.listen(7070);

then you can call zing() with PHP like this:

// Connect to DNode server running in port 7070 and call 
// Zing with argument 33
$dnode = new DNode\DNode();
$dnode->connect(7070, function($remote, $connection) {
    // Remote is a proxy object that provides us all methods
    // from the server
    $remote->zing(33, function($n) use ($connection) {
        echo "n = {$n}\n";
        // Once we have the result we can close the connection
        $connection->end();
    });
});

 

Henri's full announcement includes additional (temptingly) simple code samples for implementing a DNode server in PHP, and communicating bidirectionally in PHP using DNode. Or head over to github for the whole (nicely documented) project.

 

Comments

Yaron Levy replied on Mon, 2012/06/11 - 1:01pm

Let the comments permeate your code and you will be a happier PHPer in the future. Use single line comments for quick notes about a tricky part in your code and use multiple line comments when you need to describe something in greater depth than a simple note.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.