承接 basho/protobuf 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

basho/protobuf

Composer 安装命令:

composer require basho/protobuf

包简介

Protocol Buffer support for PHP

README 文档

README

Packagist Build Status

Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. It might be used in file formats and RPC protocols.

PHP Protobuf is Google's Protocol Buffers implementation for PHP with a goal to provide high performance, including a protoc plugin to generate PHP classes from .proto files. The heavy-lifting (a parsing and a serialization) is done by a PHP extension.

  1. Installation
  2. Documentation
  3. Contributing
  4. Roadmap
  5. License and Authors
  6. References

Installation

Dependencies

  • PHP 5.4 or above
  • Protobuf protoc compiler 2.6 or above
  • Protobuf message version proto2

Composer Install

Install From Source

  1. Clone the source code
    git clone https://github.com/allegro/php-protobuf
    
  2. Go to the source code directory
    cd php-protobuf
    
  3. Build and install the PHP extension (follow instructions at php.net)
  4. Install protoc plugin dependencies
    composer install
    

Documentation

  1. Assume you have a file foo.proto

    message Foo
    {
        required int32 bar = 1;
        optional string baz = 2;
        repeated float spam = 3;
    }
    
  2. Compile foo.proto

    php protoc-gen-php.php foo.proto
    
  3. Create Foo message and populate it with some data

    require_once 'Foo.php';
    
    $foo = new Foo();
    $foo->setBar(1);
    $foo->setBaz('two');
    $foo->appendSpam(3.0);
    $foo->appendSpam(4.0);
  4. Serialize a message to a string

    $packed = $foo->serializeToString();
  5. Parse a message from a string

    $parsedFoo = new Foo();
    try {
        $parsedFoo->parseFromString($packed);
    } catch (Exception $ex) {
        die('Oops.. there is a bug in this example, ' . $ex->getMessage());
    }
  6. Let's see what we parsed out

    $parsedFoo->dump();

    It should produce output similar to the following:

    Foo {
      1: bar => 1
      2: baz => 'two'
      3: spam(2) =>
        [0] => 3
        [1] => 4
    }
    
  7. If you would like you can reset an object to its initial state

    $parsedFoo->reset();

Compilation

Use protoc-php.php script to compile your proto files. It requires extension to be installed.

php protoc-php.php foo.proto

Specify --use-namespaces or -n option to generate classes using native PHP namespaces.

php protoc-php.php -n foo.proto

Package

If a proto file is compiled with a -n / --use-namespaces option a package is represented as an namespace. Otherwise message and enum name is prefixed with it separated by underscore. The package name is composed of a respective first-upper-case parts separated by underscore.

Message and enum name

  • underscore separated name is converted to CamelCased
  • embedded name is composed of parent message name separated by underscore

Message interface

PHP Protobuf module implements ProtobufMessage class which encapsulates protocol logic. Message compiled from proto file extends this class providing message field descriptors. Based on these descriptors ProtobufMessage knows how to parse and serialize messages of the given type.

For each field a set of accessors is generated. Methods actually accessible are different for single value fields (required / optional) and multi-value fields (repeated).

  • required / optional

      get{FIELD}()        // return field value
      set{FIELD}($value)  // set field value to $value
    
  • repeated

      append{FIELD}($value)       // append $value value to field
      clear{FIELD}()              // empty field
      get{FIELD}()                // return array of field values
      getAt{FIELD}($index)        // return field value at $index index
      getCount{FIELD}()           // return number of field values
      getIterator{FIELD}($index)  // return ArrayIterator for field values
    

{FIELD} is camel cased field name.

Enums

PHP does not natively support enum type. Hence enum is compiled to a class with set of constants.

Enum field is simple PHP integer type.

Type mapping

Range of available build-in PHP types poses some limitations. PHP does not support 64-bit positive integer type. Note that parsing big integer values might result in getting unexpected results.

Protocol Buffers types map to PHP types as follows:

| Protocol Buffers | PHP    |
| ---------------- | ------ |
| double           | float  |
| float            |        |
| ---------------- | ------ |
| int32            | int    |
| int64            |        |
| uint32           |        |
| uint64           |        |
| sint32           |        |
| sint64           |        |
| fixed32          |        |
| fixed64          |        |
| sfixed32         |        |
| sfixed64         |        |
| ---------------- | ------ |
| bool             | bool   |
| ---------------- | ------ |
| string           | string |
| bytes            |        |

Not set value is represented by null type. To unset value just set its value to null.

Parsing

To parse message create message class instance and call its parseFromString method passing it prior to the serialized message. Errors encountered are signaled by throwing Exception. Exception message provides detailed explanation. Required fields not set are silently ignored.

$packed = /* serialized FooMessage */;
$foo = new FooMessage();

try {
    $foo->parseFromString($packed);
} catch (Exception $ex) {
    die('Parse error: ' . $e->getMessage());
}

$foo->dump(); // see what you got

Serialization

To serialize message call serializeToString method. It returns a string containing protobuf-encoded message. Errors encountered are signaled by throwing Exception. Exception message provides detailed explanation. Required field not set triggers an error.

$foo = new FooMessage()
$foo->setBar(1);

try {
    $packed = $foo->serializeToString();
} catch (Exception $ex) {
    die 'Serialize error: ' . $e->getMessage();
}

/* do some cool stuff with protobuf-encoded $packed */

Dumping

There might be situations you need to investigate what actual content of the given message is. What var_dump gives on message instance is somewhat obscure.

ProtobufMessage class comes with dump method which prints out a message content to the standard output. It takes one optional argument specifying whether you want to dump only set fields. By default it dumps only set fields. Pass false as argument to dump all fields. Format it produces is similar to var_dump.

Example

  • foo.proto

      message Foo
      {
          required int32 bar = 1;
          optional string baz = 2;
          repeated float spam = 3;
      }
    
  • pb_proto_foo.php

      php protoc-php.php foo.proto
    
  • foo.php

      <?php
          require_once 'pb_proto_foo.php';
    
          $foo = new Foo();
          $foo->setBar(1);
          $foo->setBaz('two');
          $foo->appendSpam(3.0);
          $foo->appendSpam(4.0);
    
          $packed = $foo->serializeToString();
    
          $foo->clear();
    
          try {
              $foo->parseFromString($packed);
          } catch (Exception $ex) {
              die('Oops.. there is a bug in this example');
          }
    
          $foo->dump();
      ?>
    

php foo.php should produce following output:

Foo {
  1: bar => 1
  2: baz => 'two'
  3: spam(2) =>
    [0] => 3
    [1] => 4
}

License and Authors

Copyright (c) 2017 Allegro Group (Original Authors) Copyright (c) 2017 Basho Technologies, Inc.

Licensed under the Apache License, Version 2.0 (the "License"). For more details, see License.

References

basho/protobuf 适用场景与选型建议

basho/protobuf 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.93k 次下载、GitHub Stars 达 5, 最近一次更新时间为 2017 年 02 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「data」 「serialization」 「allegro」 「protobuf」 「proto」 「protocol buffers」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 basho/protobuf 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 basho/protobuf 我们能提供哪些服务?
定制开发 / 二次开发

基于 basho/protobuf 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.93k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 35
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 17
  • Forks: 263
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2017-02-02