Protocol buffer on php

Posted by figo on February 24, 2016

First, install protobuf from source

$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ ./autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.

Second, install php-protocolbuffers

$ git clone https://github.com/chobie/php-protocolbuffers.git
$ cd php-protocolbuffers
$ phpize
$ ./configure
$ make
$ sudo make install

please add following line to your php.ini

$ sudo vi /etc/php/fpm-php5.6/ext/protocolbuffers.ini
extension=protocolbuffers.so
$ sudo vi /etc/php/cli-php5.6/ext/protocolbuffers.ini
extension=protocolbuffers.so
$ sudo ln -s /etc/php/fpm-php5.6/ext/protocolbuffers.ini /etc/php/fpm-php5.6/ext-active/protocolbuffers.ini
$ sudo ln -s /etc/php/cli-php5.6/ext/protocolbuffers.ini /etc/php/cli-php5.6/ext-active/protocolbuffers.ini

Third, install composer.phar

$ curl -s http://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin

Fourth, install protoc-gen-php

$ git clone https://github.com/chobie/protoc-gen-php.git
$ cd https://github.com/chobie/protoc-gen-php.git

add protocolbuffers/protoc-gen-php entry to your global composer.json ($HOME/.composer/composer.json)

{
"require": {
"protocolbuffers/protoc-gen-php": "dev-master"
}
}

install with composer

$ composer.phar global install

set PATH (add this line to your .bashrc or .zshrc.)

$ export PATH=$HOME/.composer/vendor/bin/:$PATH

Fifth, just make a demo demo .proto file definition

package openviewmobile;
message Person
{
required int32 user_id = 1;
optional string name = 2;
}

okay, let’s generate php classes with protoc

$ protoc --php_out . person.proto

when you want to use openviewmobile\Person class, you just do require person.proto.php.

setUserId(1234);
$person->setName("chobie");
$raw = $person->serializeToString();
echo $raw
?>

Google Protocol Buffers Official Doc
php-protocolbuffers wiki
Protocol Buffers – Google’s data interchange format