CakeFest 2024: The Official CakePHP Conference

Примеры

Пример #1 Пример сервера Yar

<?php

/* Предположим, что это страница может быть доступна по http://example.com/operator.php */

class Operator {

/**
* Складываем два операнда
* @param interge
* @return interge
*/
public function add($a, $b) {
return
$this->_add($a, $b);
}

/**
* Вычитаем
*/
public function sub($a, $b) {
return
$a - $b;
}

/**
* Умножаем
*/
public function mul($a, $b) {
return
$a * $b;
}

/**
* Защищённый метод
* @param interge
* @return interge
*/
protected function _add($a, $b) {
return
$a + $b;
}
}

$server = new Yar_Server(new Operator());
$server->handle();
?>

Пример #2 Обращаемся к серверу из браузера (запрос GET)

Вывод приведённого примера будет похож на:

Информация о сервере Yar

Пример #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 exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Пример #4 Пример конкурирующих клиентов Yar

<?php
function callback($ret, $callinfo) {
echo
$callinfo['method'] , " result: ", $ret , "\n";
}

/* регистрируем асинхронные вызовы к удалённым сервисам */
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();
?>

Вывод приведённого примера будет похож на:

mul result: 4
sub result: 1
add result: 3
add a note

User Contributed Notes 1 note

up
-2
124960772 at qq dot com
8 years ago
<?php
function callback($ret, $callinfo) {
echo
$callinfo['method'] , " result: ", $ret , "\n";
}

/* 注册一个异步调用 */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */
Yar_Concurrent_Client::loop();
/* 重置call ,否则上面的call会调用*/
Yar_Concurrent_Client::reset();
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::loop();

?>
To Top