• This repository has been archived on 12/Jan/2021
  • Stars
    star
    912
  • Rank 48,094 (Top 1.0 %)
  • Language
    PHP
  • License
    Apache License 2.0
  • Created about 11 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP Protobuf - Google's Protocol Buffers for PHP

This repository is no longer maintained

Since Google's official Protocol Buffers supportsย PHP language, it's unjustifiable to maintain this project. Please refer to Protocol Buffers for PHP language support.

PHP Protobuf - Google's Protocol Buffers for PHP

Overview

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.

Requirements

  • PHP 7.0 or above (for PHP 5 support refer to php5 branch)
  • Pear's Console_CommandLine (for the protoc plugin)
  • Google's protoc compiler version 2.6 or above

Getting started

Installation

  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
    

Usage

  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();

Guide

Compilation

PHP Protobuf comes with Google's protoc compiler plugin. You can run in directly:

php protoc-gen-php.php -o output_dir foo.proto

or pass it to the protoc:

protoc --plugin=protoc-gen-allegrophp=protoc-gen-php.php --allegrophp_out=output_dir foo.proto

On Windows use protoc-gen-php.bat instead.

Command line options

  • -o out, --out=out - the destination directory for generated files (defaults to the current directory).
  • -I proto_path, --proto_path=proto_path - the directory in which to search for imports.
  • --protoc=protoc - the protoc compiler executable path.
  • -D define, --define=define - define a generator option (i.e. -Dnamespace='Foo\Bar\Baz').

Generator options

  • namespace - the namespace to be used by the generated PHP classes.

Message class

The classes generated during the compilation are PSR-0 compliant (each class is put into it's own file). If namespace generator option is not defined then a package name (if present) is used to create a namespace. If the package name is not set then a class is put into global space.

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

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

  • required / optional

      get{FIELD}()        // return a field value
      has{FIELD}()        // check whether a field is set
      set{FIELD}($value)  // set a field value to $value
    
  • repeated

      append{FIELD}($value)       // append $value to a field
      clear{FIELD}()              // empty field
      get{FIELD}()                // return an array of field values
      getAt{FIELD}($index)        // return a field value at $index index
      getCount{FIELD}()           // return a number of field values
      has{FIELD}()                // check whether a field is set
      getIterator{FIELD}()        // return an ArrayIterator
    

{FIELD} is a camel cased field name.

Enum

PHP does not natively support enum type. Hence enum is represented by the PHP integer type. For convenience enum is compiled to a class with set of constants corresponding to its possible values.

Type mapping

The 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 (x86_64):

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

Protocol Buffers types map to PHP types as follows (x86):

| Protocol Buffers | PHP                         |
| ---------------- | --------------------------- |
| double           | float                       |
| float            |                             |
| ---------------- | --------------------------- |
| int32            | int                         |
| uint32           |                             |
| sint32           |                             |
| fixed32          |                             |
| sfixed32         |                             |
| ---------------- | --------------------------- |
| int64            | if val <= PHP_INT_MAX       |
| uint64           | then value is stored as int |
| sint64           | otherwise as double         |
| fixed64          |                             |
| 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 a message class instance and call its parseFromString method passing it a serialized message. The 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 a message call serializeToString method. It returns a string containing protobuf-encoded message. The errors encountered are signaled by throwing Exception. Exception message provides detailed explanation. A 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 */

Debugging

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

The 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 an argument to dump all fields. Format it produces is similar to var_dump.

Alternatively you can use printDebugString() method which produces output in protocol buffers text format.

IDE Helper and Auto-Complete Support

To integrate this extension with your IDE (PhpStorm, Eclipse etc.) and get auto-complete support, simply include stubs\ProtobufMessage.php anywhere under your project root.

Known issues

References

Acknowledgments

More Repositories

1

bigcache

Efficient cache for gigabytes of data written in Go.
Go
7,122
star
2

ralph

Ralph is the CMDB / Asset Management system for data center and back office hardware.
Python
2,121
star
3

tipboard

Tipboard - in-house, tasty, local dashboarding system
JavaScript
1,105
star
4

hermes

Fast and reliable message broker built on top of Kafka.
Java
787
star
5

allRank

allRank is a framework for training learning-to-rank neural models based on PyTorch.
Python
775
star
6

turnilo

Business intelligence, data exploration and visualization web application for Druid, formerly known as Swiv and Pivot
TypeScript
698
star
7

axion-release-plugin

Gradle release & version management plugin.
Groovy
538
star
8

node-worker-nodes

A node.js library to run cpu-intensive tasks in a separate processes and not block the event loop.
JavaScript
484
star
9

typescript-strict-plugin

Typescript plugin that allows turning on strict mode in specific files or directories.
TypeScript
302
star
10

json-avro-converter

JSON to Avro conversion tool designed to make migration to Avro easier.
Groovy
270
star
11

embedded-elasticsearch

Tool that ease up creation of integration tests with Elasticsearch
Java
269
star
12

vaas

VaaS
Python
229
star
13

grunt-maven-plugin

Grunt + Maven integration done right
Java
214
star
14

allegro-api

Issue tracker and wiki for Allegro REST API
206
star
15

tradukisto

A Java i18n library created to convert numbers to their word representations.
Groovy
195
star
16

marathon-consul

Integrates Marathon apps with Consul service discovery.
Go
189
star
17

restapi-guideline

Allegro REST API Guideline.
CSS
174
star
18

bigflow

A Python framework for data processing on GCP.
Python
114
star
19

handlebars-spring-boot-starter

Spring Boot auto-configuration for Handlebars
Groovy
109
star
20

envoy-control

Envoy Control is a platform-agnostic, production-ready Control Plane for Service Mesh based on Envoy Proxy.
Kotlin
96
star
21

akubra

Simple solution to keep a independent S3 storages in sync
Go
85
star
22

elasticsearch-analysis-morfologik

Morfologik Polish Lemmatizer plugin for Elasticsearch
Java
81
star
23

ecto-cursor-based-stream

Elixir library that allows for cursor-based streaming of Ecto records, that does not require database transaction.
Elixir
71
star
24

opel

OPEL - asynchronous expression language
Java
66
star
25

HerBERT

HerBERT is a BERT-based Language Model trained on Polish Corpora using only MLM objective with dynamic masking of whole words.
60
star
26

fogger

Fogger - a library to create blurred background under Android's UI elements
Java
60
star
27

mesos-executor

Customizable Apache Mesos task executor
Go
49
star
28

selena

SELENA is a tool used to test website performance by measuring response times or verifying the content of replies.
JavaScript
45
star
29

elasticsearch-reindex-tool

Elasticsearch reindexing tool.
Java
44
star
30

kafka-offset-monitor-graphite

Graphite reporter for Kafka Offset Monitor.
Scala
44
star
31

cassandra-modeling-kata

Cassandra Modeling Kata
Java
37
star
32

dotnet-utils

C#
33
star
33

swift-junit

A Swift library for creating JUnit XML test results that can be interpreted by tools such as Bamboo or Jenkins. Macos and Linux ready.
Swift
29
star
34

slinger

Slinger - deep linking library for Android
Java
28
star
35

django-powerdns-dnssec

Django application managing PowerDNS database
Python
27
star
36

ralph-cli

Command-line interface for the Ralph system.
Go
26
star
37

mongo-migration-stream

Tool for online migrations of MongoDB databases.
Kotlin
26
star
38

allms

A versatile and powerful library designed to streamline the process of querying LLMs
Python
26
star
39

allegro.tech

TypeScript
23
star
40

hacktoberfest-dashboard

Allegro Hactoberfest activity dashboard
TypeScript
21
star
41

quanta

Fast image optimization as a service, based on mozjpeg, written in Swift
C
21
star
42

klejbenchmark-baselines

Fine-tuning scripts for evaluating transformer-based models on KLEJ benchmark.
Python
20
star
43

bigcache-bench

Benchmarks for BigCache project
Go
20
star
44

pyhermes

The Python interface to the Hermes message broker.
Python
19
star
45

swiftbox

SwiftBox is a package that helps building Swift/Vapor microservices.
Swift
19
star
46

json-logic-kmp

Kotlin multiplatform JsonLogic expressions evaluation engine. Targets iOS and JVM (also Android).
Kotlin
19
star
47

consul-registration-hook

Hook that can be used for synchronous registration and deregistration in Consul discovery service on Kubernetes or Mesos cluster with Allegro executor
Go
18
star
48

marathon-appcop

Marathon applications law enforcement
Go
18
star
49

newrelic-gradle-plugin

Newrelic Gradle plugin.
Groovy
17
star
50

map-with-indifferent-access

Elixir
17
star
51

grunt-maven-npm

npm tasks for grunt-maven-plugin 1.2+
JavaScript
16
star
52

leader-only-spring-boot-starter

Java
15
star
53

redux-storage-decorator-engines

Composing decorator for redux-storage to use different storage types
JavaScript
15
star
54

spunit

Spunit โ€“ Spock elegance in Kotlin JUnit 5 tests
Kotlin
14
star
55

cosmosdb-utils

A collection of useful Azure CosmosDb SDK v3 extensions and utilities, developed as part of Allegro Pay product.
C#
13
star
56

envoy-perf-pprof

Convenient Envoy on-CPU performance analysis with perf and pprof.
Dockerfile
13
star
57

prometheus-net-metrics

C#
12
star
58

dotnet-sdk

C#
12
star
59

camus-compressor

Camus Compressor merges files created by Camus and saves them in a compressed format.
Java
12
star
60

consul-recipes

Java library for interacting with Consul.
Java
12
star
61

blog

SCSS
11
star
62

ralph_pricing

A pricing module for Ralph
Python
11
star
63

solr-fast-collapsing-query-parser

Java
9
star
64

inkpy-jinja

Generate PDF documents from ODT templates.
Python
8
star
65

allegro-tech-labs-microservices

Allegro Tech Labs Microservices workshop materials
Java
8
star
66

klejbenchmark-allegroreviews

Allegro Reviews is a sentiment analysis dataset, consisting of 11,588 product reviews written in Polish and extracted from Allegro.pl - a popular e-commerce marketplace.
8
star
67

TypedListAdapter

Kotlin
7
star
68

logextractx

Python
7
star
69

solr-ids-export-plugin

Java
6
star
70

django-bob

Django bob is a set of django helpers, widgets and form filters for Ralph DCIM/CMDB project .
JavaScript
6
star
71

toper

PHP Rest client based on popular Guzzle Rest Client.
PHP
6
star
72

atm-event-app

ATM event application
JavaScript
5
star
73

application-insights

5
star
74

graphql-extended-audit-intstrumentation

Java
5
star
75

votakvot

Python
5
star
76

banana-split

JavaScript
5
star
77

warsztaty-podstawy-ml-03-2019

Machine learning basics workshop
Jupyter Notebook
4
star
78

selena-agent

Agent for Selena
Python
4
star
79

vaas-registration-hook

Go
3
star
80

swiftbox-config

Swift
3
star
81

braincode

HTML
3
star
82

oauth-mock

Kotlin
3
star
83

atm-hero-generator

JavaScript
2
star
84

swiftbox-metrics-statsd

Swift
2
star
85

eslint-plugin-test-comments

TypeScript
2
star
86

client-side-logic-dsl

Kotlin
2
star
87

parallel-test-execution-workshop

Resources for Parallel test execution workshop
Groovy
2
star
88

couchbase-commons

Kotlin
1
star
89

ml

TypeScript
1
star
90

hermes-page

Hermes OpenSource page.
HTML
1
star
91

json-cache

Java
1
star
92

swiftbox-logging

Swift
1
star
93

podcast.allegro.tech

CSS
1
star
94

axion-release-example

Kotlin
1
star
95

jobs-conf

allegro.tech jobs postings
HTML
1
star
96

allegro-tech-labs-iot

Allegro Tech Labs IoT workshop materials
Python
1
star
97

versionlens.nvim

1
star