本篇將會說明PHP中處理Protocol Buffers資料的相關問題。
Protocol Buffers 是一種輕巧高效的結構化資料儲存格式,可用於結構化資料串列化,很適合做資料儲存或 RPC 資料交換格式。它可用於通訊協定、資料儲存等領域的語言無關、平台無關、可擴展的序列化結構資料格式。目前提供了 C 、Java、Python 三種語言的 API。
安裝protoc編譯器
下載安裝
$ wget https://github.com/google/protobuf/releases/download/v2.5.0/protobuf-2.5.0.tar.gz $ tar zxvf protobuf-2.5.0.tar.gz $ cd protobuf-2.5.0 $ ./configure --prefix=/usr/local/protobuf $ sudo make $ sudo make install
安裝驗證:
$ /usr/local/protobuf/bin/protoc --version libprotoc 2.5.0
php擴充功能
安裝php擴充功能
$ wget https://pecl.php.net/get/protocolbuffers-0.2.6.tgz $ tar zxvf protocolbuffers-0.2.6.tgz $ cd protocolbuffers-0.2.6 $ phpize $ ./configure $ sudo make $ sudo make install
php.ini設定檔中新增: extension = "protocolbuffers.so"
$ php -m | grep protocolbuffers
protocolbuffers
protoc外掛程式##
$ mkdir ~/code/app$ cd ~/code/app$ composer require protocolbuffers/protoc-gen-php
$ vim demo.proto syntax = "proto2"; package Proto.Demo; message OrderInfo { required string name = 1 ; required int32 age = 2; required string amount = 3; } message UserInfo { required int32 uid = 1; required string address = 2; }
$ vim demo.proto.php<?phpspl_autoload_register(function($name){ static $classmap; if (!$classmap) { $classmap = array( 'Proto\Demo\OrderInfo' => '/Proto/Demo/OrderInfo.php', 'Proto\Demo\UserInfo' => '/Proto/Demo/UserInfo.php', // @@protoc_insertion_point(autoloader_scope:classmap) ); } if (isset($classmap[$name])) { require __DIR__ . DIRECTORY_SEPARATOR . $classmap[$name]; } }); call_user_func(function(){ $registry = \ProtocolBuffers\ExtensionRegistry::getInstance(); // @@protoc_insertion_point(extension_scope:registry)}); $oi = new Proto\Demo\OrderInfo(); $oi->setName('Jack'); $oi->setAge(28); $oi->setAmount('500');//压缩数据$protoData = $oi->serializeToString(); var_dump("压缩数据:"); var_dump($protoData);//获取到$age的值$obj = Proto\Demo\OrderInfo::parseFromString($protoData); var_dump("获取数据:"); var_dump($obj->getName()); var_dump($obj->getAge()); var_dump($obj->getAmount());
$ php demo.proto.php string(15) "压缩数据:"string(13) " Jack500"string(15) "获取数据:"string(4) "Jack"string(2) "28"string(3) "500"
以上是PHP中處理Protocol Buffers數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!