PHP7 Protobuf安装使用

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

https://developers.google.com/protocol-buffers/
 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值