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
相關文章
相關標籤/搜索