1.版本环境
系统:Ubuntu 14.04.5
PHP版本:PHP 7.1.7
protoc:libprotoc 3.6.1
php-protobuf:3.6.1
2.安装
2.1 PHP请自行安装,这里不做描述
2.2 protobuf安装
php protobuf扩展安装
以下可以自行选择是否按照,如果是没有安装这些类库,请执行
sudo apt-get install -y php-pear php5-dev autoconf automake libtool make gcc
sudo pecl install protobuf-{VERSION},这里VERSION可以自行选择,我这里是
sudo pecl install protobuf-3.6.1
这里查看php的config位置
php --ini
然后把 extension="protobuf.so"加到配置文件,重启php-fpm即可
查看是否安装成功
php -m |grep protobuf
Protoc安装:
下载地址:https://github.com/protocolbuffers/protobuf/releases
我这里选择:
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip
解压
unzip protoc-3.6.1-linux-x86_64.zip
cd protoc-3.6.1
ln bin/protoc /usr/bin/protoc
查看protoc版本号
protoc --version
编写一个protobuf文件
//addressbook.proto
// [START declaration]
syntax = "proto3";
package php_protobuf_lib;
// [START messages]
message Person {
string name = 1;
int32 id = 2; // Unique ID number for this person.
string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
repeated PhoneNumber phones = 4;
}
// Our address book file is just one of these.
message AddressBook {
repeated Person people = 1;
}
// [END messages]
生成php-protobuf文件
protoc --php_out=out_dir address_book.proto
执行后会生成一下文件:
会生成,GPBMetadata,Php_protobuf_lib目录文件
现在就可以使用啦(最好使用composer来把文件引入,方便管理),
$person = new \Php_protobuf_lib\Person();
$person->setId(mt_rand(1,1000));
$person->setName('Gary');
$person->setEmail('1031965173@qq.com');
$phoneNumber = new \Php_protobuf_lib\Person\PhoneNumber();
$phoneNumber->setNumber(15112080392);
$phoneNumber->setType(\Php_protobuf_lib\Person\PhoneType::MOBILE);
$person->setPhones([$phoneNumber]);
$request = $person->serializeToString();
$recvPerson = new \Php_protobuf_lib\Person();
$recvPerson->mergeFromString($request);
echo $recvPerson->getId()."\t".$recvPerson->getName();
相关文档地址:
protobuf message:https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message.Message-class