git clone https://github.com/allegro/php-protobuf.git php-protobuf
cd php-protobuf/
phpize
make
make instal
找到php.in,加入這行代碼:extension=/usr/lib64/php/modules/protobuf.so 重啓服務器,使用phpinfo()查看是否已經安裝拓展
新建一個簡單的proto文件:
vim test.proto
輸入以下內容:
message PhoneNumber {
required string number = 1;
required int32 type = 2;
}
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
repeated PhoneNumber phone = 4;
optional double money = 5;
}
message AddressBook {
repeated Person person = 1;
}
編譯。注意,這裏需要引用到protoc-php.php這個文件,注意路徑。
php ./php-protobuf-master/protoc-php.php test.proto
編譯成功後會在當前目錄生成一個pbprototest.php文件
如果ls沒有顯示文件,可能是隱藏文件 使用ls -a
這裏會繼承ProtobufMessage類,它是在protobuf.so中自動加載的。 寫一個測試類來測試一下:
<?php
require_once 'pb_proto_test.php';
$foo = new Person();
$foo->setName('hellojammy');
$foo->setId(2);
$foo->setEmail('[email protected]');
$foo->setMoney(1988894.995);
$phone_num = new PhoneNumber();
$phone_num->setNumber('1351010xxxx');
$phone_num->setType(3);
$foo->appendPhone($phone_num);
//$foo->appendPhone(2);
$packed = $foo->serializeToString();
//echo $packed;exit;
#$foo->clear();
echo "-----------src------------\n";
echo $foo->getName() ."\n";
echo $foo->getPhone()[0]->getNumber() ."\n";
$foo->dump();
echo "------------------------\n\n\n";
try {
$p = new Person();
$p->parseFromString($packed);
echo "------------parsed-------\n";
echo $p->getName() ."\n";
echo $p->getEmail() ."\n";
echo $p->getMoney() ."\n";
echo $p->getId() . "\n";
echo $p->getPhone()[0]->getNumber() ."\n";
//$p->dump();
echo "------------------------\n";
//print_r($xiao);
} catch (Exception $ex) {
die('Upss.. there is a bug in this example');
}
運行
php text.php
可以看到輸出:
-----------src------------
hellojammy
1351010xxxx
Person {
1: name => 'hellojammy'
2: id => 2
3: email => '[email protected]'
4: phone(1) =>
[0] =>
PhoneNumber {
1: number => '1351010xxxx'
2: type => 3
}
5: money => 1988894.995
}
------------------------
------------parsed-------
hellojammy
1988894.995
2
1351010xxxx
------------------------
假如出現提示../php-protobuf/protoc-php.php requires protobuf extension installed to run
/alidata/server/php/bin/php
爲了瞭解protobuf的壓縮原理,我特意安裝了protobuf-c
這兩個size是4和15,最後一位是結束符
如果用protobuf序列化後,總長度是18
節省了一個結束符,排列更加緊密