PHP怎么读写protobuf3

发布时间:2021-07-23 17:36:05 作者:chen
来源:亿速云 阅读:114

这篇文章主要介绍“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文件:

生成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”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. php读写分离的实现方法
  2. 如何在PHP中读写文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php protobuf3

上一篇:js如何通过类来修改css样式

下一篇:css如何设置超链接文本为白色

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》