blob: 2d3c4d311deec914a536e4db00d66de8ec1296cc [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.
6- Use the PHP gRPC API to write a simple client for your service.
7
8It assumes that you have read the [Getting started](https://github.com/grpc/grpc-common) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview).
9
10This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon.
11
12## Why use gRPC?
13
14Our 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.
15
16With gRPC we can define our 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. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
17
18## Example code and setup
19
20The example code for our tutorial is in [grpc/grpc-common/php/route_guide](https://github.com/grpc/grpc-common/tree/master/php/route_guide). To download the example, clone the `grpc-common` repository by running the following command:
21```shell
22$ git clone https://github.com/grpc/grpc-common.git
23```
24
25Then change your current directory to `grpc-common/php/route_guide`:
26```shell
27$ cd grpc-common/php/route_guide
28```
29
30You also should have the relevant tools installed to generate the client interface code - if you don't already, follow the setup instructions in [the PHP quick start guide](https://github.com/grpc/grpc-common/tree/master/php).
31
32Please note that currently we only support gRPC clients implemented in PHP. Please see other supported languages (e.g. [Node.js](https://github.com/grpc/grpc-common/tree/master/node/route_guide)) to see how gRPC servers are implemented.
33
34
35## Defining the service
36
37Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc-common)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto).
38
39To define a service, you specify a named `service` in your .proto file:
40
41```protobuf
42service RouteGuide {
43 ...
44}
45```
46
47Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
48
49- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
50```protobuf
51 // Obtains the feature at a given position.
52 rpc GetFeature(Point) returns (Feature) {}
53```
54
55- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
56```protobuf
57 // Obtains the Features available within the given Rectangle. Results are
58 // streamed rather than returned at once (e.g. in a response message with a
59 // repeated field), as the rectangle may cover a large area and contain a
60 // huge number of features.
61 rpc ListFeatures(Rectangle) returns (stream Feature) {}
62```
63
64- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a server-side streaming method by placing the `stream` keyword before the *request* type.
65```protobuf
66 // Accepts a stream of Points on a route being traversed, returning a
67 // RouteSummary when traversal is completed.
68 rpc RecordRoute(stream Point) returns (RouteSummary) {}
69```
70
71- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. 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.
72```protobuf
73 // Accepts a stream of RouteNotes sent while a route is being traversed,
74 // while receiving other RouteNotes (e.g. from other users).
75 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
76```
77
78Our .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:
79```protobuf
80// Points are represented as latitude-longitude pairs in the E7 representation
81// (degrees multiplied by 10**7 and rounded to the nearest integer).
82// Latitudes should be in the range +/- 90 degrees and longitude should be in
83// the range +/- 180 degrees (inclusive).
84message Point {
85 int32 latitude = 1;
86 int32 longitude = 2;
87}
88```
89
90
91## Generating client stub from proto files
92
93The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool.
94
95```sh
96$ cd grpc-common/php
97$ php composer.phar install
98$ cd vendor/datto/protobuf-php
99$ gem install rake ronn
100$ rake pear:package version=1.0
101$ sudo pear install Protobuf-1.0.tgz
102```
103
104To generate the client stub implementation .php file:
105
106```sh
107$ cd php/route_guide
108$ protoc-gen-php -i . -o . ./route_guide.proto
109```
110
111A `route_guide.php` file will be generated in the `php/route_guide` directory. You do not need to modify the file.
112
113To load the generated client stub file, simply `require` it in your PHP application:
114
115```php
116require dirname(__FILE__) . '/route_guide.php';
117```
118
119Once you've done this, the client classes are in the `examples\` namespace (e.g. `examples\RouteGuideClient`).
120
121
122<a name="client"></a>
123## Creating the client
124
125In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [grpc-common/php/route_guide/route_guide_client.php](https://github.com/grpc/grpc-common/blob/master/php/route_guide/route_guide_client.php). Again, please consult other languages (e.g. [Node.js](https://github.com/grpc/grpc-common/blob/master/node/route_guide/) to see how to start the route guide example server.
126
127### Creating a stub
128
129To call service methods, we first need to create a *stub*. To do this, we just need to call the RouteGuide stub constructor, specifying the server address and port.
130
131```php
132$client = new examples\RouteGuideClient(new Grpc\BaseStub('localhost:50051', []));
133```
134
135### Calling service methods
136
137Now let's look at how we call our service methods.
138
139#### Simple RPC
140
141Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method.
142
143```php
144$point = new examples\Point();
145$point->setLatitude(409146138);
146$point->setLongitude(-746188906);
147list($feature, $status) = $client->GetFeature($point)->wait();
148```
149
150As 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.
151
152```php
153 print sprintf("Found %s \n at %f, %f\n", $feature->getName(),
154 $feature->getLocation()->getLatitude() / COORD_FACTOR,
155 $feature->getLocation()->getLongitude() / COORD_FACTOR);
156```
157
158#### Streaming RPCs
159
160Now 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:
161
162```php
163 $lo_point = new examples\Point();
164 $hi_point = new examples\Point();
165
166 $lo_point->setLatitude(400000000);
167 $lo_point->setLongitude(-750000000);
168 $hi_point->setLatitude(420000000);
169 $hi_point->setLongitude(-730000000);
170
171 $rectangle = new examples\Rectangle();
172 $rectangle->setLo($lo_point);
173 $rectangle->setHi($hi_point);
174
175 $call = $client->ListFeatures($rectangle);
176 // an iterator over the server streaming responses
177 $features = $call->responses();
178 foreach ($features as $feature) {
179 // process each feature
180 } // the loop will end when the server indicates there is no more responses to be sent.
181```
182
183The `$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.
184
185The client-side streaming method `RecordRoute` is similar, except there we pass the method an iterator and get back a `examples\RouteSummary`.
186
187```php
188 $points_iter = function($db) {
189 for ($i = 0; $i < $num_points; $i++) {
190 $point = new examples\Point();
191 $point->setLatitude($lat);
192 $point->setLongitude($long);
193 yield $point;
194 }
195 };
196 // $points_iter is an iterator simulating client streaming
197 list($route_summary, $status) =
198 $client->RecordRoute($points_iter($db))->wait();
199```
200
201Finally, let's look at our bidirectional streaming RPC `routeChat()`. In this case, we just pass a context to the method and get back a `Duplex` stream object, which we can use to both write and read messages.
202
203```php
204$call = $client->RouteChat();
205```
206
207To write messages from the client:
208
209```php
210 foreach ($notes as $n) {
211 $route_note = new examples\RouteNote();
212 $call->write($route_note);
213 }
214 $call->writesDone();
215```
216
217To read messages from the server:
218
219```php
220 while ($route_note_reply = $call->read()) {
221 // process $route_note_reply
222 }
223```
224
225Each 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.
226
227## Try it out!
228
229Run the client (in a different terminal):
230```shell
231$ ./run_route_guide_client.sh
232```