HproseLaravelPHP实战

laravel中使用hprose 远程对象

2017-08-29  本文已影响406人  banbans

在你的 composer 项目中的 composer.json 文件中,添加这部分:


"require": {

    "hprose/hprose": ">=2.0.0"

}


就可以了。

使用composer update 命令更新扩展包

1.在服务器端在app目录下 创建Services目录(可手动创建)

创建UserService.php

public function init(){
       addMethod('test',$this);    //添加test方法  传入实例化对象,则是添加实例化方法
      //$server->addMethod('test', 'UserService');  //传入类名  则是添加静态方法
       $server->start();
}
public function test(){
      return 'hello';
}

路由设置,在api路由中添加

Route::post('test', function (Request $request) {

      $server = new \App\Services\UserService();

      $server->init();  //开启服务

})->middleware('api');

2.在客户端远程调用,同样安装扩展包之后

public function index(Request $request){

      //服务端路由在api路由中配置,则此处路由应加上api/test

      //实例化可选参数 加上false 即创建创建一个同步的 HTTP 客户端

      //不写false  为创建一个异步的 HTTP 客户端

      $user =new Client('http://127.0.0.1:81/api/test',false);

      $res=$user->test();

      return $res;

}

需要注意的是,异步的HTTP 客户端是不能往外返回值的

可以使用静态方法来创建

$client = Client::create('http://localhost:81/api/test');

$client->test()->then(function($result){

  echo $result;

});

这样 会直接输出:hello

上一篇下一篇

猜你喜欢

热点阅读