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:
- protoc: the protobuf compiler binary to generate PHP classes for your messages and service definition
- grpc_php_plugin: a plugin for
protoc
to generate the service stub classes.
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
|
|
Simple gRPC PHP demos and examples:
rokclimb15/php-grpc-demo php-grpc-demo/helloworld_client.php