您的位置:首页 > 其它

用Swoole框架实现WebService和远程接口调用RPC

2011-07-04 16:05 731 查看
利用Swoole框架中提供的WebService类和RestClient类,可以很方便地实现Webservice和远程接口调用。
可以用在,网站对外提供API,或者大型网站系统内部不同模块之间接口调用。
代码简洁易懂,支持远程函数调用,面向对象的方法、属性编程

服务器端:
<?php
require '../../config.php';
require LIBPATH.'/system/WebService.php';

$web = new WebService;

//设定可远程调用的客户端IP
$web->access_ip[] = '127.0.0.1';
$web->access_ip[] = '192.168.1.102';
//注册函数
$web->reg_func('testme','test');
//注册类
$web->reg_class('world','Foo');
//注册验证方式
$web->reg_auth('rpc_user_check');
//运行
$web->run();

/**
* 检测用户是否有权限进行远程调用
* @param $user
* @param $pass
* @return unknown_type
*/
function rpc_user_check($user,$getpass)
{
//这里也可以换成查询数据库表的操作
$passdb['test'] = '123456';

//存在用户,而且密码正确
$passhash = Auth::mkpasswd($user,$passdb[$user]);
if(isset($passdb[$user]) and $passhash==$getpass) return true;
else return false;
}

function test($name)
{
return array('hello','world!');
}

class Foo
{
public $index;

function getinfo($param)
{
return 'my index is '.$this->index.'; param :'.$param;
}
}

客户端:
<?php
require '../../config.php';
import('#web.RestClient');

$server_url = "http://top.com/test/web/rpc.php";
$user = 'test';
$pass = '123456';
$rest = new RestClient($server_url,$user,$pass);
//$rest->debug = true;

$result1 = $rest->func('testme');

$obj = $rest->create('world');
$obj->index = 'page';
$result2 = $obj->getinfo('delete');

debug($result1,$result2);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: