示例 #1 Yar 服务端示例
<?php
/* 假设这个页面可以通过 http://example.com/operator.php 访问 */
class Operator {
/**
* Add two operands
* @param integer
* @return integer
*/
public function add($a, $b) {
return $this->_add($a, $b);
}
/**
* Sub
*/
public function sub($a, $b) {
return $a - $b;
}
/**
* Mul
*/
public function mul($a, $b) {
return $a * $b;
}
/**
* Protected methods will not be exposed
* @param integer
* @return integer
*/
protected function _add($a, $b) {
return $a + $b;
}
}
$server = new Yar_Server(new Operator());
$server->handle();
?>示例 #2 通过浏览器访问服务端(GET 请求)
当向服务地址发起 GET 请求时,Yar 会渲染一个信息页面, 列出执行对象的每一个公开方法及其文档注释。 该行为由 yar.expose_info 配置项控制。
以上示例的输出类似于:
示例 #3 Yar 客户端示例
<?php
$client = new Yar_Client("http://example.com/operator.php");
/* 直接调用 */
var_dump($client->add(1, 2));
/* 通过 call() 调用 */
var_dump($client->call("add", array(3, 2)));
/* _add 无法被调用: 它不是公开方法 */
var_dump($client->_add(1, 2));
?>以上示例的输出类似于:
int(3) int(5) PHP Fatal error: Uncaught Yar_Server_Request_Exception: call to undefined api Operator::_add() in *
示例 #4 Yar 并发客户端示例
<?php
function callback($ret, $callinfo) {
echo $callinfo['method'], " result: ", $ret, "\n";
}
function error_callback($type, $error, $callinfo) {
error_log("[$type] $error");
}
/* 注册对远程服务的异步调用 */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "mul", array(2, 2), "callback");
/* 发送所有请求并等待响应 */
Yar_Concurrent_Client::loop("callback", "error_callback");
?>以上示例的输出类似于:
mul result: 4 sub result: 1 add result: 3
示例 #5 Yar TCP 客户端示例
除了 HTTP 之外,Yar_Client 还可以 通过 TCP 或 Unix socket 与兼容 Yar 协议的服务器通信, 例如一个由 Yar C 框架实现的服务。 远程服务器必须实现相同的 Yar 二进制协议。
<?php
$client = new Yar_Client("tcp://127.0.0.1:8600");
var_dump($client->add(1, 2));
?>