美文网首页PHP笔记PHP实战PHP进阶
PHP中处理Protocol Buffers数据

PHP中处理Protocol Buffers数据

作者: 零一间 | 来源:发表于2017-07-14 21:44 被阅读92次

    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
    

    测试:

    编写proto文件

    $ 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;
    }
    

    生成php类库代码

    $ /usr/local/protobuf/bin/protoc --plugin=vendor/bin/protoc-gen-php --php_out=. -I. demo.proto
    

    编写测试文件:

    $ vim demo.proto.php
    
    <?php
    
    spl_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数据

        本文链接:https://www.haomeiwen.com/subject/kdlohxtx.html