blob: e5230ae4e438035a7c9dea6ff4221835071a0bad [file] [log] [blame] [view]
Stanley Cheung5fd27c92015-06-11 09:29:06 -07001#gRPC Basics: PHP
2
3This tutorial provides a basic PHP programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
4
5- Define a service in a .proto file.
Stanley Cheung45e43802015-06-16 08:59:07 -07006- Generate client code using the protocol buffer compiler.
Stanley Cheung5fd27c92015-06-11 09:29:06 -07007- Use the PHP gRPC API to write a simple client for your service.
8
Stanley Cheung45e43802015-06-16 08:59:07 -07009It assumes a passing familiarity with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto2 version of the protocol buffers language.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070010
Stanley Cheung0a268212015-08-27 14:38:38 -070011Also 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](examples/node/route_guide).
Stanley Cheung5bcf4672015-06-18 08:23:17 -070012
Stanley Cheung5fd27c92015-06-11 09:29:06 -070013This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon.
14
Stanley Cheung45e43802015-06-16 08:59:07 -070015- [Why use gRPC?](#why-grpc)
16- [Example code and setup](#setup)
Stanley Cheung5bcf4672015-06-18 08:23:17 -070017- [Try it out!](#try)
Stanley Cheung45e43802015-06-16 08:59:07 -070018- [Defining the service](#proto)
19- [Generating client code](#protoc)
20- [Creating the client](#client)
Stanley Cheung45e43802015-06-16 08:59:07 -070021
22
23<a name="why-grpc"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -070024## Why use gRPC?
25
Stanley Cheung45e43802015-06-16 08:59:07 -070026With gRPC you can define your service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. You also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070027
Stanley Cheung5fd27c92015-06-11 09:29:06 -070028
Stanley Cheung45e43802015-06-16 08:59:07 -070029<a name="setup"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -070030## Example code and setup
31
Stanley Cheung0a268212015-08-27 14:38:38 -070032The example code for our tutorial is in [examples/php/route_guide](examples/php/route_guide). To download the example, clone this repository by running the following command:
Stanley Cheung5fd27c92015-06-11 09:29:06 -070033```shell
Stanley Cheung0a268212015-08-27 14:38:38 -070034$ git clone https://github.com/grpc/grpc.git
Stanley Cheung5fd27c92015-06-11 09:29:06 -070035```
36
Stanley Cheung0a268212015-08-27 14:38:38 -070037Then change your current directory to `examples/php/route_guide`:
Stanley Cheung5fd27c92015-06-11 09:29:06 -070038```shell
Stanley Cheung0a268212015-08-27 14:38:38 -070039$ cd examples/php/route_guide
Stanley Cheung5fd27c92015-06-11 09:29:06 -070040```
41
Stanley Cheung45e43802015-06-16 08:59:07 -070042Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070043
Stanley Cheung45e43802015-06-16 08:59:07 -070044You also should have the relevant tools installed to generate the client interface code (and a server in another language, for testing). You can obtain the latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc).
45
Stanley Cheung5bcf4672015-06-18 08:23:17 -070046
47<a name="try"></a>
48## Try it out!
49
50To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the Node.js server in this repository:
51
52```shell
53$ cd ../../node
54$ npm install
55$ cd route_guide
56$ nodejs ./route_guide_server.js --db_path=route_guide_db.json
57```
58
59Run the PHP client (in a different terminal):
60
61```shell
62$ ./run_route_guide_client.sh
63```
64
Stanley Cheung45e43802015-06-16 08:59:07 -070065The next sections guide you step-by-step through how this proto service is defined, how to generate a client library from it, and how to create a client stub that uses that library.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070066
67
Stanley Cheung45e43802015-06-16 08:59:07 -070068<a name="proto"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -070069## Defining the service
70
Stanley Cheung0a268212015-08-27 14:38:38 -070071First let's look at how the service we're using is defined. A gRPC *service* and its method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file for our example in [`examples/protos/route_guide.proto`](examples/protos/route_guide.proto).
Stanley Cheung5fd27c92015-06-11 09:29:06 -070072
73To define a service, you specify a named `service` in your .proto file:
74
75```protobuf
76service RouteGuide {
77 ...
78}
79```
80
Stanley Cheung45e43802015-06-16 08:59:07 -070081Then you define `rpc` methods inside your service definition, specifying their request and response types. Protocol buffers let you define four kinds of service method, all of which are used in the `RouteGuide` service:
Stanley Cheung5fd27c92015-06-11 09:29:06 -070082
Stanley Cheung45e43802015-06-16 08:59:07 -070083- A *simple RPC* where the client sends a request to the server and receives a response later, just like a normal remote procedure call.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070084```protobuf
85 // Obtains the feature at a given position.
86 rpc GetFeature(Point) returns (Feature) {}
87```
88
Stanley Cheung45e43802015-06-16 08:59:07 -070089- A *response-streaming RPC* where the client sends a request to the server and gets back a stream of response messages. You specify a response-streaming method by placing the `stream` keyword before the *response* type.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070090```protobuf
91 // Obtains the Features available within the given Rectangle. Results are
92 // streamed rather than returned at once (e.g. in a response message with a
93 // repeated field), as the rectangle may cover a large area and contain a
94 // huge number of features.
95 rpc ListFeatures(Rectangle) returns (stream Feature) {}
96```
97
Stanley Cheung45e43802015-06-16 08:59:07 -070098- A *request-streaming RPC* where the client sends a sequence of messages to the server. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a request-streaming method by placing the `stream` keyword before the *request* type.
Stanley Cheung5fd27c92015-06-11 09:29:06 -070099```protobuf
100 // Accepts a stream of Points on a route being traversed, returning a
101 // RouteSummary when traversal is completed.
102 rpc RecordRoute(stream Point) returns (RouteSummary) {}
103```
104
Stanley Cheung45e43802015-06-16 08:59:07 -0700105- A *bidirectional streaming RPC* where both sides send a sequence of messages to the other. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700106```protobuf
107 // Accepts a stream of RouteNotes sent while a route is being traversed,
108 // while receiving other RouteNotes (e.g. from other users).
109 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
110```
111
112Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
113```protobuf
114// Points are represented as latitude-longitude pairs in the E7 representation
115// (degrees multiplied by 10**7 and rounded to the nearest integer).
116// Latitudes should be in the range +/- 90 degrees and longitude should be in
117// the range +/- 180 degrees (inclusive).
118message Point {
119 int32 latitude = 1;
120 int32 longitude = 2;
121}
122```
123
124
Stanley Cheung45e43802015-06-16 08:59:07 -0700125<a name="protoc"></a>
126## Generating client code
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700127
Stanley Cheung45e43802015-06-16 08:59:07 -0700128The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool. To install the tool:
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700129
130```sh
Stanley Cheung0a268212015-08-27 14:38:38 -0700131$ cd examples/php
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700132$ php composer.phar install
133$ cd vendor/datto/protobuf-php
134$ gem install rake ronn
135$ rake pear:package version=1.0
136$ sudo pear install Protobuf-1.0.tgz
137```
138
139To generate the client stub implementation .php file:
140
141```sh
142$ cd php/route_guide
143$ protoc-gen-php -i . -o . ./route_guide.proto
144```
145
146A `route_guide.php` file will be generated in the `php/route_guide` directory. You do not need to modify the file.
147
148To load the generated client stub file, simply `require` it in your PHP application:
149
150```php
151require dirname(__FILE__) . '/route_guide.php';
152```
153
Stanley Cheung45e43802015-06-16 08:59:07 -0700154The file contains:
155- All the protocol buffer code to populate, serialize, and retrieve our request and response message types.
156- A class called `examples\RouteGuideClient` that lets clients call the methods defined in the `RouteGuide` service.
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700157
158
159<a name="client"></a>
160## Creating the client
161
Stanley Cheung0a268212015-08-27 14:38:38 -0700162In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [examples/php/route_guide/route_guide_client.php](examples/php/route_guide/route_guide_client.php).
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700163
Stanley Cheung45e43802015-06-16 08:59:07 -0700164### Constructing a client object
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700165
Stanley Cheung45e43802015-06-16 08:59:07 -0700166To call service methods, we first need to create a client object, an instance of the generated `RouteGuideClient` class. The constructor of the class expects the server address and port we want to connect to:
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700167
168```php
169$client = new examples\RouteGuideClient(new Grpc\BaseStub('localhost:50051', []));
170```
171
172### Calling service methods
173
174Now let's look at how we call our service methods.
175
176#### Simple RPC
177
178Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method.
179
180```php
Stanley Cheung45e43802015-06-16 08:59:07 -0700181 $point = new examples\Point();
182 $point->setLatitude(409146138);
183 $point->setLongitude(-746188906);
184 list($feature, $status) = $client->GetFeature($point)->wait();
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700185```
186
187As you can see, we create and populate a request object, i.e. an `examples\Point` object. Then, we call the method on the stub, passing it the request object. If there is no error, then we can read the response information from the server from our response object, i.e. an `examples\Feature` object.
188
189```php
190 print sprintf("Found %s \n at %f, %f\n", $feature->getName(),
191 $feature->getLocation()->getLatitude() / COORD_FACTOR,
192 $feature->getLocation()->getLongitude() / COORD_FACTOR);
193```
194
195#### Streaming RPCs
196
197Now let's look at our streaming methods. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s:
198
199```php
200 $lo_point = new examples\Point();
201 $hi_point = new examples\Point();
202
203 $lo_point->setLatitude(400000000);
204 $lo_point->setLongitude(-750000000);
205 $hi_point->setLatitude(420000000);
206 $hi_point->setLongitude(-730000000);
207
208 $rectangle = new examples\Rectangle();
209 $rectangle->setLo($lo_point);
210 $rectangle->setHi($hi_point);
211
212 $call = $client->ListFeatures($rectangle);
213 // an iterator over the server streaming responses
214 $features = $call->responses();
215 foreach ($features as $feature) {
216 // process each feature
217 } // the loop will end when the server indicates there is no more responses to be sent.
218```
219
220The `$call->responses()` method call returns an iterator. When the server sends a response, a `$feature` object will be returned in the `foreach` loop, until the server indiciates that there will be no more responses to be sent.
221
222The client-side streaming method `RecordRoute` is similar, except there we pass the method an iterator and get back a `examples\RouteSummary`.
223
224```php
225 $points_iter = function($db) {
226 for ($i = 0; $i < $num_points; $i++) {
227 $point = new examples\Point();
228 $point->setLatitude($lat);
229 $point->setLongitude($long);
230 yield $point;
231 }
232 };
233 // $points_iter is an iterator simulating client streaming
234 list($route_summary, $status) =
235 $client->RecordRoute($points_iter($db))->wait();
236```
237
Stanley Cheung45e43802015-06-16 08:59:07 -0700238Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `BidiStreamingCall` stream object, which we can use to both write and read messages.
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700239
240```php
241$call = $client->RouteChat();
242```
243
244To write messages from the client:
245
246```php
247 foreach ($notes as $n) {
248 $route_note = new examples\RouteNote();
249 $call->write($route_note);
250 }
251 $call->writesDone();
252```
253
254To read messages from the server:
255
256```php
257 while ($route_note_reply = $call->read()) {
258 // process $route_note_reply
259 }
260```
261
262Each 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 operate completely independently.