这篇文章主要介绍“PHP怎么读写protobuf3”,在日常操作中,相信很多人在PHP怎么读写protobuf3问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”PHP怎么读写protobuf3”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
protobuf(Google Protocol Buffers)是Google提供一个具有高效的协议数据交换格式工具库(类似Json),但相比于Json,Protobuf有更高的转化效率,时间效率和空间效率都是JSON的3-5倍。
在proto3中,可以直接使用protoc命令生成PHP代码。生成的PHP代码不能直接使用,还需要Protobuf的PHP库支持。
下面通过一个例子演示下PHP怎么使用protobuf。首先定义proto文件:
syntax = "proto3";
package lm;
message helloworld
{
int32 id = 1; // ID
string str = 2; // str
int32 opt = 3; // optional field
}
注意这里采用的是proto3的语法,和proto2不太一样,required和optional的限定已经没有了,所有的字段都是可选的。proto3相比proto2有什么区别,可以参照 这篇文章。
接着用protoc生成PHP文件:
protoc --php_out=./ hello.proto
会看到生成了一个hello.pb.php文件:
namespace Lm;
use Google\Protobuf\Internal\DescriptorPool;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
class helloworld extends \Google\Protobuf\Internal\Message
{
....
}
阅读下里面的代码,发现它use了Google\Protobuf下的类,这是一个PHP库,可以去下载:
https://github.com/google/protobuf/tree/master/php/src/Google/Protobuf
也可以用composer引入到项目中,推荐用composer引入,因为composer会帮你自动生成Autoloader:
composer require google/protobuf
采用composer方式引入google/protobuf之后,项目中会出现一个vendor目录。在自己的代码中includevendor下的autoload.php,以及刚才生成的helloworld.pb.php文件,就可以进行二进制的读写了。
有了google/protobuf库的帮助,PHP读写protobuf格式的二进制还是很方便的。
利用protobuf写入数据到二进制文件:
<?php
include 'vendor/autoload.php';
include 'hello.pb.php';
$from = new \Lm\helloworld();
$from->setId(1);
$from->setStr('foo bar, this is a message');
$from->setOpt(29);
$data = $from->serializeToString();
file_put_contents('data.bin', $data);
读取同样的二进制文件:
<?php
include 'vendor/autoload.php';
include 'hello.pb.php';
$data = file_get_contents('data.bin');
$to = new \Lm\helloworld();
$to->mergeFromString($data);
echo $to->getId() . PHP_EOL;
echo $to->getStr() . PHP_EOL;
echo $to->getOpt() . PHP_EOL;
到此,关于“PHP怎么读写protobuf3”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。