PHPackages                             jacknoordhuis/php-protobuf - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. jacknoordhuis/php-protobuf

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jacknoordhuis/php-protobuf
==========================

Google's Protocol Buffers for PHP

v0.12.3(8y ago)09BSD-3-ClausePHPPHP &gt;=5.3

Since Jul 18Pushed 7y ago1 watchersCompare

[ Source](https://github.com/JackNoordhuis/php-protobuf)[ Packagist](https://packagist.org/packages/jacknoordhuis/php-protobuf)[ Docs](https://github.com/allegro/php-protobuf)[ RSS](/packages/jacknoordhuis-php-protobuf/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (9)Used By (0)

PHP Protobuf - Google's Protocol Buffers for PHP
================================================

[](#php-protobuf---googles-protocol-buffers-for-php)

Overview
--------

[](#overview)

[Protocol Buffers](http://code.google.com/p/protobuf/ "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

[](#requirements)

- PHP 7.0 or above (for PHP 5 support refer to [php5](https://github.com/allegro/php-protobuf/tree/php5) branch)
- Pear's Console\_CommandLine (for the protoc plugin)
- Google's protoc compiler version 2.6 or above

Getting started
---------------

[](#getting-started)

### Installation

[](#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](http://php.net/manual/en/install.pecl.phpize.php))
4. Install protoc plugin dependencies

    ```
    composer install

    ```

### Global Composer installation

[](#global-composer-installation)

1. Locate your global composer directory (usually ~/.composer)
2. Add the git repository to the composer.json

    ```
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/JackNoordhuis/php-protobuf"
        }
    ]

    ```
3. Add the library as a global dependency

    ```
    "require": [
       "jacknoordhuis/php-protobuf": "dev-master"
    ]

    ```
4. Finally, run `composer global update` to install the required dependencies
5. You can now run the `protoc-gen-php` command from anywhere

### Usage

[](#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
-----

[](#guide)

### Compilation

[](#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

[](#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

[](#generator-options)

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

### Message class

[](#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

[](#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

[](#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 parseFromString($packed);
} catch (Exception $ex) {
    die('Parse error: ' . $e->getMessage());
}

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

### Serialization

[](#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

[](#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
------------------------------------

[](#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
------------

[](#known-issues)

- [maps](https://developers.google.com/protocol-buffers/docs/proto#maps) are not fully supported ([\#73](https://github.com/allegro/php-protobuf/issues/73))
- [oneof](https://developers.google.com/protocol-buffers/docs/proto#oneof) is not supported ([\#72](https://github.com/allegro/php-protobuf/issues/72))
- [groups](https://developers.google.com/protocol-buffers/docs/proto#groups) are not supported

References
----------

[](#references)

- [Protocol Buffers](http://code.google.com/p/protobuf/ "Protocol Buffers")

Acknowledgments
---------------

[](#acknowledgments)

- PHP7 support ([Sergey](https://github.com/serggp))

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 61% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~100 days

Recently: every ~9 days

Total

7

Last Release

2978d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/10399774?v=4)[Jack Noordhuis](/maintainers/JackNoordhuis)[@JackNoordhuis](https://github.com/JackNoordhuis)

---

Top Contributors

[![hjagodzinski](https://avatars.githubusercontent.com/u/3833077?v=4)](https://github.com/hjagodzinski "hjagodzinski (36 commits)")[![JackNoordhuis](https://avatars.githubusercontent.com/u/10399774?v=4)](https://github.com/JackNoordhuis "JackNoordhuis (6 commits)")[![nyoung](https://avatars.githubusercontent.com/u/4152009?v=4)](https://github.com/nyoung "nyoung (5 commits)")[![cujo](https://avatars.githubusercontent.com/u/398518?v=4)](https://github.com/cujo "cujo (5 commits)")[![serggp](https://avatars.githubusercontent.com/u/10685183?v=4)](https://github.com/serggp "serggp (2 commits)")[![dcelasun](https://avatars.githubusercontent.com/u/144373?v=4)](https://github.com/dcelasun "dcelasun (2 commits)")[![deejay1](https://avatars.githubusercontent.com/u/41211?v=4)](https://github.com/deejay1 "deejay1 (1 commits)")[![cdddcw](https://avatars.githubusercontent.com/u/5449804?v=4)](https://github.com/cdddcw "cdddcw (1 commits)")[![Alex-D](https://avatars.githubusercontent.com/u/426843?v=4)](https://github.com/Alex-D "Alex-D (1 commits)")

---

Tags

dataprotocol bufferspb

### Embed Badge

![Health badge](/badges/jacknoordhuis-php-protobuf/health.svg)

```
[![Health](https://phpackages.com/badges/jacknoordhuis-php-protobuf/health.svg)](https://phpackages.com/packages/jacknoordhuis-php-protobuf)
```

###  Alternatives

[fakerphp/faker

Faker is a PHP library that generates fake data for you.

3.9k358.5M3.5k](/packages/fakerphp-faker)[dflydev/dot-access-data

Given a deep data structure, access data by dot notation.

718359.1M86](/packages/dflydev-dot-access-data)[mbezhanov/faker-provider-collection

A collection of custom providers for the Faker library

2138.6M24](/packages/mbezhanov-faker-provider-collection)[php-units-of-measure/php-units-of-measure

A PHP library for converting between standard units of measure.

3123.4M20](/packages/php-units-of-measure-php-units-of-measure)[amenadiel/jpgraph

Composer Friendly, full refactor of JpGraph, library to make graphs and charts

1492.2M7](/packages/amenadiel-jpgraph)[jbzoo/data

An extended version of the ArrayObject object for working with system settings or just for working with data arrays

891.6M23](/packages/jbzoo-data)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
