DNode 是一個基於異步消息的 RPC 框架,它讓不同語言、不同運行環境之間的相互調用變得輕鬆。本文就來演示如何讓 PHP 與 Node.js 通過 DNode 彼此通信。
一、安裝 DNode
Node.js 端安裝:
$ sudo npm install dnode
PHP 端則借助 Composer 安裝 DNode 的 PHP 版本。先下載 Composer:
$ wget https://getcomposer.org/composer.phar
新建一個 composer.json 文件,填入:
{
"require": {
"dnode/dnode": "0.2.0"
}
}
然後執行安裝:
$ sudo php composer.phar install
二、用 Node.js 創建簡單的 server.js
var dnode = require('dnode');
var server = dnode({
zing: function (n, cb) { cb(n * 100) }
});
server.listen(7070);
三、用 PHP 創建客戶端 client.php,注意要引用剛才安裝好的 autoload.php:
<?php
// Connect to DNode server running in port 7070 and call
// Zing with argument 33
require 'lib/vendor/autoload.php';
// This is the class we're exposing to DNode
class Temp
{
// Compute the client's temperature and stuff that value into the callback
public function temperature($cb)
{
}
}
$loop = new React\EventLoop\StreamSelectLoop();
$dnode = new DNode\DNode($loop, new Temp());
$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();
});
});
$loop->run();
?>
四、啟動服務器端
$ node server.js
五、運行客戶端去調用服務端
$ php client.php
這時客戶端會遠程調用服務端的計算方法,並輸出結果:
n = 3300
由此可見,PHP 完全可以把 Node.js 提供的方法當成本地函數一樣調用,DNode 在兩者之間架起了一座便利的桥梁。