PHP code example of dustinfog / parpc
1. Go to this page and download the library: Download dustinfog/parpc library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dustinfog / parpc example snippets
$router = new \Parpc\RemoteProcedureRouter();
$router->route();
//创建远程环境
$context = new \Parpc\RemoteContext("http://127.0.0.1:9000/");
//测试函数
function hello($who)
{
return "hello," . $who;
}
//执行远程函数hello
echo $context->hello("world") . PHP_EOL;
class Dog{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$dog = $context->createObject("Dog", array("Bingo"));
echo "There was a farmer had a dog, " . $dog->getName() . " was its name oh" . PHP_EOL;
$dog = new Dog("Bingo");
echo "There was a farmer had a dog, " . $dog->getName() . " was its name oh" . PHP_EOL;
> /** @var Dog $dog 我们知道这并没有真的创建一个Dog实例,但并不妨碍我们把它注释为Dog类型 */
> $dog = $context->createObject("Dog", array("Bingo"));
>
try {
$cat = $context->createObject("Cat", array("kitty"));
echo "Was there a cat with name " . $cat->getName();
} catch(\Parpc\RemoteException $e) {
echo "没有喵星人的事儿: " . $e->getMessage() . PHP_EOL);
}
// 并发调用需要一个额外的caller
$caller = new \Parpc\RemoteProcedureCaller();
// 这里与同步调用亦有所不同,这里没有采用new关键字,而是用一个工厂方法来简化创建RemoteContext的复杂度
$context = $caller->createContext("http://127.0.0.1:9000/");
//普通函数
$context->hello()->onSuccess(function($ret){
echo $ret . PHP_EOL;
})->onComplete("onComplete");
//远程对象
$dog = $context->createObject("Dog", array("bingo"));
$dog->getName()->onSuccess(function($ret){
echo "There was a farmer had a dog, " . $ret . " was its name oh" . PHP_EOL;
})->onComplete("onComplete");
//异常处理
$cat = $context->createObject("Cat", array("kitty"));
$cat->getName()->onSuccess(function($ret){
echo "Was there a cat with name " . $ret;
})->onFail(function(\Parpc\RemoteException $e){
echo "没有喵星人的事儿: " . $e->getMessage() . PHP_EOL);
})->onComplete("onComplete");
//一次性批量提交
$caller->commit();
function onComplete(\Parpc\RemoteProcedure $procedure) {
echo "无论成败,风雨无阻,执行完成过程" . $procedure;
})
> /** @var Dog $dog */
> $dog = $context->createObject("Dog", array("bingo"));
> /** @var \Parpc\RemoteProcedure $procedure */
> $procedure = $dog->getName();
> $procedure->onSuccess ...
>
//只允许本地程序调用
$router->addSecurityValidator(new \Parpc\RemoteAddrValidator(array("127.0.0.1")));