PHP GRPC Server

Latest version: pecl install openswoole-4.11.1

GRPC is a high performance, open source universal RPC framework. Open Swoole GRPC for PHP is a high performance integration solution for building cloud-native multiple language microservices architecture.

GRPC Server for PHP is the server side of OpenSwoole GRPC for PHP.

Features

  • Native GRPC implementation compliant
  • PHP/PHP-FPM GRPC client compliant
  • Open Swoole GRPC Compiler provided
  • GRPC unary mode support
  • GRPC server side stream mode
  • GRPC server side interceptors

GRPC protocol

GRPC is a wire protocol based on HTTP2 protocol with multiplexing support. You can use multiple concurrent communication channels and streams on the same connection. Compared with RPC services upon HTTP protocol, GRPC saves the cost from establishing and mantain many TCP connections.

GRPC protocol looks like this:

HEADERS (flags = END_HEADERS)
:method = POST
:scheme = http
:path = /google.pubsub.v2.PublisherService/CreateTopic
:authority = pubsub.googleapis.com
grpc-timeout = 1S
content-type = application/grpc+proto
grpc-encoding = gzip
authorization = Bearer y235.wef315yfh138vh31hv93hv8h3v

DATA (flags = END_STREAM)
<Length-Prefixed Message>

HEADERS (flags = END_HEADERS)
:status = 200
grpc-encoding = gzip
content-type = application/grpc+proto

DATA
<Length-Prefixed Message>

HEADERS (flags = END_STREAM, END_HEADERS)
grpc-status = 0 # OK
trace-proto-bin = jher831yy13JHy3hc

PHP GRPC Server Example

Define Protocol Buffers protocols of your service

When implementing a GRPC service runing in PHP GRPC server, you get started with .proto file with the defination of the service.

syntax = "proto3";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

service Stream {
  rpc FetchResponse (HelloRequest) returns (stream HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

Generate PHP stub codes with OpenSwoole GRPC Compiler

Then you can generate PHP stub codes from the .proto and OpenSwoole GRPC Compiler.

Then implement the logic of the service in the generated PHP service files like the following Helloworld GreeterService example:

# src/Helloworld/GreeterService.php
namespace Helloworld;

use OpenSwoole\GRPC;

class GreeterService implements GreeterInterface
{
    /**
     * @throws GRPC\Exception\InvokeException
     */
    public function SayHello(GRPC\ContextInterface $ctx, HelloRequest $request): HelloReply
    {
        $name = $request->getName();
        $out  = new HelloReply();
        $out->setMessage('hello ' . $name);

        return $out;
    }
}

You can find the a full Open Swoole GRPC server example at OpenSwoole GRPC server and clients example.

Last updated on March 31, 2022