protobuf 学习

protobuf是何物

Protocol Buffers - Google's data interchange format
think XML, but smaller, faster, and simpler

protobuf 是google出品的数据格式转换转换协议,支持多种语言,也能够将其理解成一种数据序列化/反序列化协议php

github地址:https://github.com/protocolbu...java

支持<font color=Blue>php、python、java、go</font>python


在php中使用protobuf

安装protobuf

mac系统使用brew安装
brew install protobuf@3.7git

安装php的protobuf扩展

pecl install protobufgithub

引入protobuf-php

composer require google/protobufcomposer

定义.proto文件

syntax="proto3";         //声明版本,3x版本支持php
package test;           //包名
message Person{
    string name=1;     //姓名
    int32  age=2;      //年龄
    bool sex=3;        //性别
}

生成php代码,将生成的文件输出到--php_out目录中
` protoc --php_out=/Users/jiao/ProjectPhp/test/protobuf test.proto
`
能够发现生成了这2个文件
image.png测试

编写测试代码ui

<?php
//require '../vendor/autoload.php';
//use Test\Person;
include 'GPBMetadata/Test.php';
include 'Test/Person.php';


$model = new Test/Person();
$model->setAge(19);
$model->setName('123');
$model->setSex('1');

$res = $model->serializeToString();
$res1 = $model->serializeToJsonString();
file_put_contents('data.bin',$res);

$bindata = file_get_contents('./data.bin');
$person = new Test\Person();
$person->mergeFromString($bindata);

echo $person->getName() . PHP_EOL;
echo $person->getAge() . PHP_EOL;
echo $person->getSex() . PHP_EOL;

输出google

小强 19 1
相关文章
相关标签/搜索