Installing Protobuf on CentOS 7

Installing Protobuf on CentOS 7

Before downloading CentOS 7, make sure to update the backup source. This can be done by executing the following command:

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

For reference, please visit: http://mirrors.aliyun.com/help/centos

Additionally, mount the EPEL source by executing the following command:

wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-8.noarch.rpm

If the version is not the same, please visit: http://dl.fedoraproject.org/pub/epel/

Then, install the EPEL repository by executing the following command:

rpm -ivh epel-release-7-8.noarch.rpm

After that, clean the yum cache and update the system:

yum clean all
yum update
yum makecache

Installing PHP Environment on CentOS 7

To install the PHP environment on CentOS 7, mount LAMP + PHPmyadmin by executing the following command:

yum install -y lamp

Mounting Composer

To mount Composer, execute the following command:

curl -sS https://getcomposer.org/installer

Then, install Composer by executing the following command:

php composer.phar --install --dir=/usr/local/bin

Installing ProtobufPHP-devel

To install ProtobufPHP-devel, clone the repository from GitHub by executing the following command:

git clone https://github.com/allegro/php-protobuf.git

Then, install the required dependencies by executing the following command:

yum install -y GCC GCC-c++
yum install -y make make

After that, install the PHP extension by executing the following command:

phpize
./configure && make install

Installing shared extensions:

echo "extension=protobuf.so" >> /etc/php.ini

Mounting Protoc

To mount Protoc, download the latest version from GitHub by executing the following command:

wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz

Then, extract and configure the package by executing the following command:

cd protobuf-2.6.1
./configure
make
make install

To verify the installation, execute the following command:

protoc --version

Testing Protobuf

To test Protobuf, create a new file called foo.proto with the following content:

message Foo {
  required int32 bar = 1;
  optional string baz = 2;
  repeated float spam = 3;
}

Then, generate the PHP code by executing the following command:

protoc-gen-php.php foo.proto

Create a new file called test.php with the following content:

setBar(1);
$Foo->setBaz('two');
$Foo->appendSpam(3.0);
$Foo->appendSpam(4.0);
$packed = $Foo->serializeToString();
$ParsedFoo = new Foo();
try {
    $ParsedFoo->parseFromString($packed);
} catch (Exception $ex) {
    die('Oops .. there is a bug in this example,' . $ex->getMessage());
}
$ParsedFoo->dump();

To execute the test case, run the following command:

php test.php

The output should be:

Foo {
  1: bar => 1
  2: baz => "two"
  3: spam (2) => [0] => 3.0
                    [1] => 4.0
}

This article was published on 2018-04-28 13:50:18.