protoc的介绍,安装
1.定义一个protoc 文件 示例:person.proto
syntax="proto3"; ????????//声明版本,3x版本支持phppackage test; ??????????//包名message Person{ ????????//Person ?生成php文件的类名 ???string name=1; ????//姓名 ???int32 ?age=2; ?????//年龄 ???bool sex=3; ???????//性别}
2.安装peotoc成功后,进入cmd 执行命令
protoc --php_out=./ person.proto
命令执行成功后,会在当前目录生成 文件 GPBMetadata/Person.php Test/Person.php
3.在php中使用protobuf需要安装php的扩展,或者使用composer 安装依赖扩展(自动生成 autoload 文件,方便)
composer require google/protobuf
4.建立测试 test.php文件,能够引入生成的php类库文件与composer 安装生成的autoload 文件,执行文件
序列化
<?phpinclude ‘vendor/autoload.php‘;include ‘GPBMetadata/Person.php‘;include ‘Test/Person.php‘;$person = new Test\Person();$person->setName("xiaozhu");$person->setAge("20");$person->setSex(true);$data = $person->serializeToString();file_put_contents(‘data.bin‘,$data);echo $data;
反序列化
<?phpinclude ‘vendor/autoload.php‘;include ‘GPBMetadata/Person.php‘;include ‘Test/Person.php‘;$person = new Test\Person();$bindata = file_get_contents(‘./data.bin‘);$person = new Test\Person();$person->mergeFromString($bindata);echo $person->getName();
php使用protobuf3
原文地址:https://www.cnblogs.com/songxuan/p/10538723.html