PHP GRPC Server

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

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.

OpenSwoole GPRC server provides the skeltons of building high performance GPRC services, normal steps:

  • Define Protocol Buffers protocols of your service
  • Generate PHP stub codes with OpenSwoole GRPC Compiler
  • Register you GPRC services on the server
  • Set up WorkerContext with API $server->withWorkerContext for database connection pools, client side pools etc internal services
  • Add middleware with API $server->addMiddleware for your middlewares such as authentication, logging etc
  • Start the GRPC server
  • Send request to the service with any GRPC clients in Java or Golang

You have to install OpenSwoole GRPC library with composer require openswoole/grpc to use this hook.

Methods

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;
    }
}

OpenSwoole GPRC server example:

<?php

use Helloworld\GreeterService;
use Helloworld\StreamService;
use OpenSwoole\GRPC\Middleware\LoggingMiddleware;
use OpenSwoole\GRPC\Middleware\TraceMiddleware;
use OpenSwoole\GRPC\Server;

// enable hooks on IO clients
co::set(['hook_flags' => OpenSwoole\Runtime::HOOK_ALL]);

$server = (new Server('127.0.0.1', 9501))
    ->register(GreeterService::class)
    ->register(StreamService::class)
    ->withWorkerContext('worker_start_time', function () {
        return time();
    })
    // use middlewares
    ->addMiddleware(new LoggingMiddleware())
    ->addMiddleware(new TraceMiddleware())
    ->set([
        'log_level' => \OpenSwoole\Constant::LOG_INFO,
    ])
    ->start();

GRPC Client side example:

<?php
declare(strict_types=1);

use Helloworld\HelloRequest;
use OpenSwoole\Constant;
use OpenSwoole\GRPC\Client;

co::set(['log_level' => Constant::LOG_ERROR]);

co::run(function () {
    $conn    = (new Client('127.0.0.1', 9501))->connect();
    $client  = new Helloworld\GreeterClient($conn);
    $message = new HelloRequest();
    $message->setName(str_repeat('x', 10));
    $out = $client->sayHello($message);
    var_dump($out->serializeToJsonString());
    $conn->close();
    echo "closed\n";
});

Last updated on February 8, 2023