create grpc client server in php

To create a gRPC client and server in PHP, you will need to follow these steps:

  1. Install gRPC PHP extension:
pecl install grpc
18 chars
2 lines
  1. Install protobuf PHP extension:
pecl install protobuf
22 chars
2 lines
  1. Create a .proto file that contains the service definition. For example, let's create a file example.proto with the following content:
syntax = "proto3";
 
service ExampleService {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
message HelloRequest {
  string name = 1;
}
 
message HelloReply {
  string message = 1;
}
195 chars
14 lines
  1. Generate the gRPC code from the .proto file. To do this, you need to use the protoc compiler and the grpc_php_plugin. For example:
protoc --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=/path/to/grpc_php_plugin example.proto
98 chars
2 lines
  1. This will generate two files: example.pb.php and example.grpc.php.

  2. Create a gRPC server. Here is an example server that implements the ExampleService:

main.php
<?php
require 'vendor/autoload.php';
require 'example.grpc.php';
 
class ExampleServiceHandler implements example\ExampleServiceServer {
 
    public function SayHello(example\HelloRequest $request): example\HelloReply {
        return new example\HelloReply(['message' => 'Hello, ' . $request->getName() . '!']);
    }
}
 
$server = new \Grpc\Server();
$server->addHttp2Port('0.0.0.0:50051');
$server->handle(new ExampleServiceHandler());
$server->run();
456 chars
16 lines
  1. Create a gRPC client to connect to the server. Here is an example client that sends a SayHello request:
main.php
<?php
require 'vendor/autoload.php';
require 'example.grpc.php';
 
$client = new example\ExampleServiceClient('localhost:50051', [
   'credentials' => \Grpc\ChannelCredentials::createInsecure(),
]);
 
$request = new example\HelloRequest(['name' => 'World']);
$response = $client->SayHello($request)->wait();
list($reply, $status) = $response;
echo $reply->getMessage() . "\n";
377 chars
13 lines

You can find more information and examples in the official gRPC PHP documentation.

related categories

gistlibby LogSnag