blob: 931dd0c68a16a7ede3c07d7076f7b6f73836f349 [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
11This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon.
12
Stanley Cheung45e43802015-06-16 08:59:07 -070013- [Why use gRPC?](#why-grpc)
14- [Example code and setup](#setup)
15- [Defining the service](#proto)
16- [Generating client code](#protoc)
17- [Creating the client](#client)
18- [Try it out!](#try)
19
20
21<a name="why-grpc"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -070022## Why use gRPC?
23
Stanley Cheung45e43802015-06-16 08:59:07 -070024With 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 -070025
Stanley Cheung5fd27c92015-06-11 09:29:06 -070026
Stanley Cheung45e43802015-06-16 08:59:07 -070027<a name="setup"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -070028## Example code and setup
29
30The 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:
31```shell
32$ git clone https://github.com/grpc/grpc-common.git
33```
34
35Then change your current directory to `grpc-common/php/route_guide`:
36```shell
37$ cd grpc-common/php/route_guide
38```
39
Stanley Cheung45e43802015-06-16 08:59:07 -070040Our 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 -070041
Stanley Cheung45e43802015-06-16 08:59:07 -070042You 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).
43
44The 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 -070045
46
Stanley Cheung45e43802015-06-16 08:59:07 -070047<a name="proto"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -070048## Defining the service
49
Stanley Cheung45e43802015-06-16 08:59:07 -070050First 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 [`grpc-common/protos/route_guide.proto`](https://github.com/grpc/grpc-common/blob/master/protos/route_guide.proto).
Stanley Cheung5fd27c92015-06-11 09:29:06 -070051
52To define a service, you specify a named `service` in your .proto file:
53
54```protobuf
55service RouteGuide {
56 ...
57}
58```
59
Stanley Cheung45e43802015-06-16 08:59:07 -070060Then 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 -070061
Stanley Cheung45e43802015-06-16 08:59:07 -070062- 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 -070063```protobuf
64 // Obtains the feature at a given position.
65 rpc GetFeature(Point) returns (Feature) {}
66```
67
Stanley Cheung45e43802015-06-16 08:59:07 -070068- 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 -070069```protobuf
70 // Obtains the Features available within the given Rectangle. Results are
71 // streamed rather than returned at once (e.g. in a response message with a
72 // repeated field), as the rectangle may cover a large area and contain a
73 // huge number of features.
74 rpc ListFeatures(Rectangle) returns (stream Feature) {}
75```
76
Stanley Cheung45e43802015-06-16 08:59:07 -070077- 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 -070078```protobuf
79 // Accepts a stream of Points on a route being traversed, returning a
80 // RouteSummary when traversal is completed.
81 rpc RecordRoute(stream Point) returns (RouteSummary) {}
82```
83
Stanley Cheung45e43802015-06-16 08:59:07 -070084- 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 -070085```protobuf
86 // Accepts a stream of RouteNotes sent while a route is being traversed,
87 // while receiving other RouteNotes (e.g. from other users).
88 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
89```
90
91Our .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:
92```protobuf
93// Points are represented as latitude-longitude pairs in the E7 representation
94// (degrees multiplied by 10**7 and rounded to the nearest integer).
95// Latitudes should be in the range +/- 90 degrees and longitude should be in
96// the range +/- 180 degrees (inclusive).
97message Point {
98 int32 latitude = 1;
99 int32 longitude = 2;
100}
101```
102
103
Stanley Cheung45e43802015-06-16 08:59:07 -0700104<a name="protoc"></a>
105## Generating client code
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700106
Stanley Cheung45e43802015-06-16 08:59:07 -0700107The 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 -0700108
109```sh
110$ cd grpc-common/php
111$ php composer.phar install
112$ cd vendor/datto/protobuf-php
113$ gem install rake ronn
114$ rake pear:package version=1.0
115$ sudo pear install Protobuf-1.0.tgz
116```
117
118To generate the client stub implementation .php file:
119
120```sh
121$ cd php/route_guide
122$ protoc-gen-php -i . -o . ./route_guide.proto
123```
124
125A `route_guide.php` file will be generated in the `php/route_guide` directory. You do not need to modify the file.
126
127To load the generated client stub file, simply `require` it in your PHP application:
128
129```php
130require dirname(__FILE__) . '/route_guide.php';
131```
132
Stanley Cheung45e43802015-06-16 08:59:07 -0700133The file contains:
134- All the protocol buffer code to populate, serialize, and retrieve our request and response message types.
135- A class called `examples\RouteGuideClient` that lets clients call the methods defined in the `RouteGuide` service.
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700136
137
138<a name="client"></a>
139## Creating the client
140
Stanley Cheung45e43802015-06-16 08:59:07 -0700141In 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).
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700142
Stanley Cheung45e43802015-06-16 08:59:07 -0700143### Constructing a client object
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700144
Stanley Cheung45e43802015-06-16 08:59:07 -0700145To 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 -0700146
147```php
148$client = new examples\RouteGuideClient(new Grpc\BaseStub('localhost:50051', []));
149```
150
151### Calling service methods
152
153Now let's look at how we call our service methods.
154
155#### Simple RPC
156
157Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method.
158
159```php
Stanley Cheung45e43802015-06-16 08:59:07 -0700160 $point = new examples\Point();
161 $point->setLatitude(409146138);
162 $point->setLongitude(-746188906);
163 list($feature, $status) = $client->GetFeature($point)->wait();
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700164```
165
166As 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.
167
168```php
169 print sprintf("Found %s \n at %f, %f\n", $feature->getName(),
170 $feature->getLocation()->getLatitude() / COORD_FACTOR,
171 $feature->getLocation()->getLongitude() / COORD_FACTOR);
172```
173
174#### Streaming RPCs
175
176Now 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:
177
178```php
179 $lo_point = new examples\Point();
180 $hi_point = new examples\Point();
181
182 $lo_point->setLatitude(400000000);
183 $lo_point->setLongitude(-750000000);
184 $hi_point->setLatitude(420000000);
185 $hi_point->setLongitude(-730000000);
186
187 $rectangle = new examples\Rectangle();
188 $rectangle->setLo($lo_point);
189 $rectangle->setHi($hi_point);
190
191 $call = $client->ListFeatures($rectangle);
192 // an iterator over the server streaming responses
193 $features = $call->responses();
194 foreach ($features as $feature) {
195 // process each feature
196 } // the loop will end when the server indicates there is no more responses to be sent.
197```
198
199The `$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.
200
201The client-side streaming method `RecordRoute` is similar, except there we pass the method an iterator and get back a `examples\RouteSummary`.
202
203```php
204 $points_iter = function($db) {
205 for ($i = 0; $i < $num_points; $i++) {
206 $point = new examples\Point();
207 $point->setLatitude($lat);
208 $point->setLongitude($long);
209 yield $point;
210 }
211 };
212 // $points_iter is an iterator simulating client streaming
213 list($route_summary, $status) =
214 $client->RecordRoute($points_iter($db))->wait();
215```
216
Stanley Cheung45e43802015-06-16 08:59:07 -0700217Finally, 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 -0700218
219```php
220$call = $client->RouteChat();
221```
222
223To write messages from the client:
224
225```php
226 foreach ($notes as $n) {
227 $route_note = new examples\RouteNote();
228 $call->write($route_note);
229 }
230 $call->writesDone();
231```
232
233To read messages from the server:
234
235```php
236 while ($route_note_reply = $call->read()) {
237 // process $route_note_reply
238 }
239```
240
241Each 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.
242
Stanley Cheung45e43802015-06-16 08:59:07 -0700243<a name="try"></a>
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700244## Try it out!
245
Stanley Cheung45e43802015-06-16 08:59:07 -0700246To 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:
247
248```shell
249$ cd ../../node
250$ npm install
251$ cd route_guide
252$ nodejs ./route_guide_server.js --db_path=route_guide_db.json
253```
254
255Run the PHP client (in a different terminal):
256
Stanley Cheung5fd27c92015-06-11 09:29:06 -0700257```shell
258$ ./run_route_guide_client.sh
259```