下载代码
git clone https://github.com/protocolbuffers/protobuf.git
安装protobuf:
./autogen.sh
./configure --prefix=/usr/local/protobuf
make
sudo make install
安装php扩展:
cd protobuf/php/ext/google/protobuf
/usr/local/php-7.1.11/bin/phpize
./configure --with-php-config=/usr/local/php-7.1.11/bin/php-config
make
sudo make install
添加配置:
/usr/local/php-7.1.11/bin/php --ini | grep php.ini
sudo vim /usr/local/php-7.1.11/etc/php.ini
extension=protobuf.so
测试:
编写proto 协议文件
vim User.proto
syntax="proto3";
message UserInfo
{
int32 id = 1;
string name = 2;
}
用protoc编译协议文件,会在当前目录下生成GPBMetadata目录和UserInfo.php文件
/usr/local/protobuf/bin/protoc --php_out=./ User.proto
安装php库:
composer require google/protobuf
编写php脚本
<?php
require('./vendor/autoload.php');
require('./UserInfo.php');
require('./GPBMetadata/User.php');
$pbUserInfo = new UserInfo();
$pbUserInfo->setId(1001);
$pbUserInfo->setName('jack');
$str = $pbUserInfo->serializeToString();
$ptTempUser = new UserInfo();
$ptTempUser->mergeFromString($str);
var_dump("id:".$ptTempUser->getId()." name:".$ptTempUser->getName());
执行代码
/usr/local/php-7.1.11/bin/php -f test.php
string(17) "id:1001 name:jack"
image.png
持续更新~
网友评论