gRPC Basics - PHP

This tutorial provides a basic PHP programmer’s introduction toworking with gRPC.

By walking through this example you’ll learn how to:

  • Define a service in a .proto file.
  • Generate client code using the protocol buffer compiler.
  • Use the PHP gRPC API to write a simple client for your service.

It assumes a passing familiarity withprotocolbuffers. Notethat the example in this tutorial uses the proto2 version of the protocolbuffers language.

Also note that currently you can only create clients in PHP for gRPC services -you can find out how to create gRPC servers in our other tutorials, e.g.Node.js.

Why use gRPC?

With gRPC you can define your service once in a .proto file and implementclients and servers in any of gRPC’s supported languages, which in turn can berun in environments ranging from servers inside Google to your own tablet - allthe complexity of communication between different languages and environments ishandled for you by gRPC. You also get all the advantages of working withprotocol buffers, including efficient serialization, a simple IDL, and easyinterface updating.

Example code and setup

The example code for our tutorial is ingrpc/grpc/examples/php/route_guide.To download the example, clone the grpc repository by running the followingcommand:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc

You need grpc-php-plugin to help you generate proto files. You can build it from source:

  1. $ cd grpc && git submodule update --init && make grpc_php_plugin

Then change your current directory to examples/php/route_guide and generate proto files:

  1. $ cd examples/php/route_guide
  2. $ ./route_guide_proto_gen.sh

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

You also should have the relevant tools installed to generate the clientinterface code (and a server in another language, for testing). You can obtainthe latter by followingthese setupinstructions.

Try it out!

To try the sample app, we need a gRPC server running locally. Let’s compile andrun, for example, the Node.js server in this repository:

  1. $ cd ../../node
  2. $ npm install
  3. $ cd dynamic_codegen/route_guide
  4. $ nodejs ./route_guide_server.js --db_path=route_guide_db.json

Run the PHP client (in a different terminal):

  1. $ ./run_route_guide_client.sh

The next sections guide you step-by-step through how this proto service isdefined, how to generate a client library from it, and how to create a clientstub that uses that library.

Defining the service

First let’s look at how the service we’re using is defined. A gRPC service andits method request and response types usingprotocolbuffers. You cansee the complete .proto file for our example inexamples/protos/route_guide.proto.

To define a service, you specify a named service in your .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then you define rpc methods inside your service definition, specifying theirrequest and response types. Protocol buffers let you define four kinds ofservice method, all of which are used in the RouteGuide service:

  • A simple RPC where the client sends a request to the server and receives aresponse later, just like a normal remote procedure call.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A response-streaming RPC where the client sends a request to the server andgets back a stream of response messages. You specify a response-streamingmethod by placing the stream keyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A request-streaming RPC where the client sends a sequence of messages to theserver. Once the client has finished writing the messages, it waits for theserver to read them all and return its response. You specify arequest-streaming method by placing the stream keyword before the _request_type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesto the other. The two streams operate independently, so clients and serverscan read and write in whatever order they like: for example, the server couldwait to receive all the client messages before writing its responses, or itcould alternately read a message then write a message, or some othercombination of reads and writes. The order of messages in each stream ispreserved. You specify this type of method by placing the stream keywordbefore both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

Generating client code

The PHP client stub implementation of the proto files can be generated by thegRPC PHP Protoc Plugin. To compile the plugin:

  1. $ make grpc_php_plugin

To generate the client stub implementation .php file:

  1. $ cd grpc
  2. $ protoc --proto_path=examples/protos \
  3. --php_out=examples/php/route_guide \
  4. --grpc_out=examples/php/route_guide \
  5. --plugin=protoc-gen-grpc=bins/opt/grpc_php_plugin \
  6. ./examples/protos/route_guide.proto

or running the helper script under the grpc/example/php/route_guide directory if you buildgrpc-php-plugin by source:

  1. $ ./route_guide_proto_gen.sh

A number of files will be generated in the examples/php/route_guide directory.You do not need to modify those files.

To load these generated files, add this section to your composer.json file underexamples/php directory

  1. "autoload": {
  2. "psr-4": {
  3. "": "route_guide/"
  4. }
  5. }

The file contains:

  • All the protocol buffer code to populate, serialize, and retrieve our requestand response message types.
  • A class called Routeguide\RouteGuideClient that lets clients call the methodsdefined in the RouteGuide service.

Creating the client

In this section, we’ll look at creating a PHP client for our RouteGuideservice. You can see our complete example client code inexamples/php/route_guide/route_guide_client.php.

Constructing a client object

To call service methods, we first need to create a client object, an instance ofthe generated RouteGuideClient class. The constructor of the class expects theserver address and port we want to connect to:

  1. $client = new Routeguide\RouteGuideClient('localhost:50051', [
  2. 'credentials' => Grpc\ChannelCredentials::createInsecure(),
  3. ]);

Calling service methods

Now let’s look at how we call our service methods.

Simple RPC

Calling the simple RPC GetFeature is nearly as straightforward as calling alocal asynchronous method.

  1. $point = new Routeguide\Point();
  2. $point->setLatitude(409146138);
  3. $point->setLongitude(-746188906);
  4. list($feature, $status) = $client->GetFeature($point)->wait();

As you can see, we create and populate a request object, i.e. anRouteguide\Point object. Then, we call the method on the stub, passing it therequest object. If there is no error, then we can read the response informationfrom the server from our response object, i.e. an Routeguide\Feature object.

  1. print sprintf("Found %s \n at %f, %f\n", $feature->getName(),
  2. $feature->getLocation()->getLatitude() / COORD_FACTOR,
  3. $feature->getLocation()->getLongitude() / COORD_FACTOR);

Streaming RPCs

Now let’s look at our streaming methods. Here’s where we call the server-sidestreaming method ListFeatures, which returns a stream of geographicalFeatures:

  1. $lo_point = new Routeguide\Point();
  2. $hi_point = new Routeguide\Point();
  3. $lo_point->setLatitude(400000000);
  4. $lo_point->setLongitude(-750000000);
  5. $hi_point->setLatitude(420000000);
  6. $hi_point->setLongitude(-730000000);
  7. $rectangle = new Routeguide\Rectangle();
  8. $rectangle->setLo($lo_point);
  9. $rectangle->setHi($hi_point);
  10. $call = $client->ListFeatures($rectangle);
  11. // an iterator over the server streaming responses
  12. $features = $call->responses();
  13. foreach ($features as $feature) {
  14. // process each feature
  15. } // the loop will end when the server indicates there is no more responses to be sent.

The $call->responses() method call returns an iterator. When the server sendsa response, a $feature object will be returned in the foreach loop, untilthe server indiciates that there will be no more responses to be sent.

The client-side streaming method RecordRoute is similar, except that we call$call->write($point) for each point we want to write from the client side andget back a Routeguide\RouteSummary.

  1. $call = $client->RecordRoute();
  2. for ($i = 0; $i < $num_points; $i++) {
  3. $point = new Routeguide\Point();
  4. $point->setLatitude($lat);
  5. $point->setLongitude($long);
  6. $call->write($point);
  7. }
  8. list($route_summary, $status) = $call->wait();

Finally, let’s look at our bidirectional streaming RPC routeChat(). In thiscase, we just pass a context to the method and get back a BidiStreamingCallstream object, which we can use to both write and read messages.

  1. $call = $client->RouteChat();

To write messages from the client:

  1. foreach ($notes as $n) {
  2. $route_note = new Routeguide\RouteNote();
  3. $call->write($route_note);
  4. }
  5. $call->writesDone();

To read messages from the server:

  1. while ($route_note_reply = $call->read()) {
  2. // process $route_note_reply
  3. }

Each side will always get the other’s messages in the order they were written,both the client and server can read and write in any order — the streams operatecompletely independently.