在 PHP 中使用 XMLRPC

这几天在研究 Moodle Network 组件,通过这个模块,各个孤立的系统被连接到了一起,实现了单点登录和资源共享(对于 e-learning 有很大的意义),通信协议是 XML-RPC,信息安全不是依赖 SSL 的方案,而是在采用了 XML 签名(不对称加密算法),想法非常好,但实现的不太完整,因为这个模块的原作者离开了在新西兰的公司,整得像个半完成作品。

今天看了一下代码,打算在这上面解决多 Moodle 系统的资源共享问题(包含点对点和 HUB 模式),之前没用过 XMLRPC,所以现在开始学一下,我用的是 PHP 的 XMLRPC 模块(比纯 PHP 实现快了不少)。

首先实现一个 XMLRPC 服务,我封装了一个简单的类:

class xmlrpc_server {
    private $server;
    public function __construct() {
        $this->server = xmlrpc_server_create();
    }
    public function add($name, $func) {
        xmlrpc_server_register_method($this->server, $name, $func);
    }
    public function run() {
        $req = file_get_contents('php://input');
        $response = xmlrpc_server_call_method($this->server, $req, null);
        echo $response;
        xmlrpc_server_destroy($this->server);
    }
}

调用这个类创建一个服务:

header('Content-Type: text/xml');
function func_add($method, $params) {
    return $params[0]+$params[1];
}
$xmlrpc = new xmlrpc_server;
$xmlrpc->add('add', 'func_add');
$xmlrpc->run();

PHP 客户端的调用是通过 HTTP 的 POST 方法,我用的是 cURL 扩展:

require_once('curl.class.php');
class xmlrpc_client {
    public function __construct($url, $autoload = false) {
        $this->connection = null;
        $this->url = $url;
        $this->connection = new curl;
        $this->methods = array();
        if ($autoload) {
            $resp = $this->call('system.listMethods', null);
            $this->methods = $resp;
        }
    }
    public function call($method, $params = null) {
        $post = xmlrpc_encode_request($method, $params);
        return xmlrpc_decode($this->connection->post($this->url, $post));
    }
}
header('Content-Type: text/plain');
$rpc = "http://10.0.0.10/api.php";
$client = new xmlrpc_client($rpc, true);
print_r($client->call('add', array(199,2)));

待续,下一步优化代码并实现 XML 签名技术。

资料:

XML Signature Syntax and Processing
OpenSSH
XML Encryption Syntax and Processing

== TO BE CONTINUED ==