具有函数重载的简单 OO 客户端
PHP 方法 test_helloworld 被转换为 xmlrpc 方法 test.helloworld。
class RpcClient {
private $_methods;
private $_context;
private $_url;
function __construct ($url, $user, $passwd) {
$auth = base64_encode(sprintf('%s:%s', $user,$passwd));
$this->_context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic $auth" ,
)
));
$this->_url = $url;
$this->registerMethod ("Test_HelloWorld");
}
function __call($methodName, $params) {
if (array_key_exists($methodName,$this->_methods)) {
// 调用 RPC 函数
$m = str_replace('_', '.', $methodName);
$r = xmlrpc_encode_request($m, $params,array('verbosity'=>'newlines_only'));
$c = $this->_context;
stream_context_set_option($c,'http','content',$r);
$f = file_get_contents($this->_url,false,$c);
$resp = xmlrpc_decode($f);
return $resp;
} else {
// 调用对象函数
call_user_method_array($methodName, $this,$params);
}
}
private function registerMethod ($method) {
$this->_methods[$method] = true;
}
}