Setup gRPC in PHP

Setup gRPC in PHP

Quick start gRPC PHP Install gRPC for PHP on Google Cloud Platform

Install pecl, pear and composer if needed:

apt install autoconf zlib1g-dev php-dev php-pear
# install if needed composer

Install and enable gRPC extension in php.ini

# install the gRPC extension
pecl install grpc
# create a file
# (cd /etc/php/*/mods-available/ && touch grpc.ini)

folder=(/etc/php/*/mods-available)

# fill in content
cat <<'EOF' > $folder/grpc.ini
; Enable gRPC extension
extension=grpc.so
EOF

Use proper way to enable extension

phpenmod grpc
service php*-fpm restart

You can also disable PHP module with phpdismod grpc and list all modules with phpquery -M.

Verify with:

php -i | grep -i grpc

Install the protobuf runtime library

For better performance with gRPC we will use protobuf C extension

# install the protobuf C extension
pecl install protobuf
folder=(/etc/php/*/mods-available)

cat <<'EOF' > $folder/protobuf.ini
; Enable protobuf C extension used by gRPC
extension=protobuf.so
EOF

phpenmod protobuf
service php*-fpm restart

In project

Use Composer to add the grpc/grpc to your project:

composer require grpc/grpc

Also needed: Protocol Buffers tool

We need the following things to get started:

  1. protoc: the protobuf compiler binary to generate PHP classes for your messages and service definition
  2. grpc_php_plugin: a plugin for protoc to generate the service stub classes.

grpc/src/php

First one is easy:

apt install -y protobuf-compiler

We also need the grpc_php_plugin to generate the client stub code from .proto service definitions.

git clone https://github.com/grpc/grpc
cd grpc
git submodule update --init
make grpc_php_plugin

cp ./grpc/bins/opt/grpc_php_plugin ./grpc/bins/opt/protobuf/protoc ./bin
rm -rf grpc

The grpc_php_plugin executable binary will be found in grpc/src/compiler/grpc_php_plugin, but I’ve copied binaries to current bin subfolder. I’ve simplified folder structure.

protoc –proto_path=../protos –php_out=. –grpc_out=. –plugin=protoc-gen-grpc=../../bins/opt/grpc_php_plugin ../protos/helloworld.proto

./grpc/bins/opt/grpc_php_plugin

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
webroot=/var/www/clients/client0/web8/web/
cd $webroot/module/kern/_voucher-crawlers
mkdir service

protoc --php_out=./service --grpc_out=./service --plugin=protoc-gen-grpc=./bin/grpc_php_plugin --proto_path=./protos  ./protos/crawler.proto

# in my case is simpler
protoc --php_out=./service --grpc_out=./service --plugin=protoc-gen-grpc=./bin/grpc_php_plugin --proto_path=$webroot/service/crawler crawler.proto

# --proto_path= : directory in which to search for imports
# --php_out=    : where to generate PHP files
# --grpc_out=
# --plugin=     : optional form NAME=PATH, plugin name is mapped to executable even if the executable's own name differs

Simple gRPC PHP demos and examples:

rokclimb15/php-grpc-demo php-grpc-demo/helloworld_client.php

date 01. Jan 0001 | modified 28. May 2021
filename: RPC » gRPC in PHP