您好,登錄后才能下訂單哦!
這篇文章主要介紹“PHP怎么讀寫(xiě)protobuf3”,在日常操作中,相信很多人在PHP怎么讀寫(xiě)protobuf3問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”P(pán)HP怎么讀寫(xiě)protobuf3”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
protobuf(Google Protocol Buffers)是Google提供一個(gè)具有高效的協(xié)議數(shù)據(jù)交換格式工具庫(kù)(類似Json),但相比于Json,Protobuf有更高的轉(zhuǎn)化效率,時(shí)間效率和空間效率都是JSON的3-5倍。
在proto3中,可以直接使用protoc命令生成PHP代碼。生成的PHP代碼不能直接使用,還需要Protobuf的PHP庫(kù)支持。
下面通過(guò)一個(gè)例子演示下PHP怎么使用protobuf。首先定義proto文件:
syntax = "proto3"; package lm; message helloworld { int32 id = 1; // ID string str = 2; // str int32 opt = 3; // optional field }
注意這里采用的是proto3的語(yǔ)法,和proto2不太一樣,required和optional的限定已經(jīng)沒(méi)有了,所有的字段都是可選的。proto3相比proto2有什么區(qū)別,可以參照 這篇文章。
接著用protoc生成PHP文件:
protoc --php_out=./ hello.proto
會(huì)看到生成了一個(gè)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 { .... }
閱讀下里面的代碼,發(fā)現(xiàn)它use了Google\Protobuf下的類,這是一個(gè)PHP庫(kù),可以去下載:
https://github.com/google/protobuf/tree/master/php/src/Google/Protobuf
也可以用composer引入到項(xiàng)目中,推薦用composer引入,因?yàn)閏omposer會(huì)幫你自動(dòng)生成Autoloader:
composer require google/protobuf
采用composer方式引入google/protobuf之后,項(xiàng)目中會(huì)出現(xiàn)一個(gè)vendor目錄。在自己的代碼中includevendor下的autoload.php,以及剛才生成的helloworld.pb.php文件,就可以進(jìn)行二進(jìn)制的讀寫(xiě)了。
有了google/protobuf庫(kù)的幫助,PHP讀寫(xiě)protobuf格式的二進(jìn)制還是很方便的。
利用protobuf寫(xiě)入數(shù)據(jù)到二進(jìn)制文件:
<?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);
讀取同樣的二進(jìn)制文件:
<?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;
到此,關(guān)于“PHP怎么讀寫(xiě)protobuf3”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。