溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP如何讀寫protobuf3

發(fā)布時間:2021-09-10 16:13:21 來源:億速云 閱讀:155 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)PHP如何讀寫protobuf3,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

protobuf(Google Protocol Buffers)是Google提供一個具有高效的協(xié)議數(shù)據(jù)交換格式工具庫(類似Json),但相比于Json,Protobuf有更高的轉(zhuǎn)化效率,時間效率和空間效率都是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的限定已經(jīng)沒有了,所有的字段都是可選的。

接著用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
{
    ....
}

閱讀下里面的代碼,發(fā)現(xiàn)它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之后,項目中會出現(xiàn)一個vendor目錄。在自己的代碼中includevendor下的autoload.php,以及剛才生成的helloworld.pb.php文件,就可以進行二進制的讀寫了。

關(guān)于“PHP如何讀寫protobuf3”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI