PHPackages                             basho/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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. basho/protobuf

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

basho/protobuf
==============

Protocol Buffer support for PHP

v1.0.1(9y ago)56.9k↓33.3%8[2 issues](https://github.com/basho/php-protobuf/issues)PHPPHP &gt;=5.3

Since May 11Pushed 9y ago17 watchersCompare

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

READMEChangelog (3)DependenciesVersions (6)Used By (0)

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

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

[![Packagist](https://camo.githubusercontent.com/bcbae6d62bd30b6da1db13974687e91be81e7dd517e4540cfaf4e81244316c0e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f626173686f2f70726f746f6275662e7376673f6d61784167653d32353932303030)](https://packagist.org/packages/basho/protobuf) [![Build Status](https://camo.githubusercontent.com/4c0c25c700b2109f1eec1443b764b398a47bf37013d96749427d2ee4b6c711f7/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f626173686f2f7068702d70726f746f6275662e706e673f6272616e63683d6d6173746572)](http://travis-ci.org/basho/php-protobuf)

[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.

1. [Installation](#installation)
2. [Documentation](#documentation)
3. [Contributing](#contributing)
4. [Roadmap](#roadmap)
5. [License and Authors](#license-and-authors)
6. [References](#references)

Installation
------------

[](#installation)

### Dependencies

[](#dependencies)

- PHP 5.4 or above
- Protobuf `protoc` compiler 2.6 or above
- Protobuf message version `proto2`

### Composer Install

[](#composer-install)

### Install From Source

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

    ```

Documentation
-------------

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

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

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

[](#message-and-enum-name)

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

### Message interface

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

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

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

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

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

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

[](#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 foo.php` should produce following output:

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

```

License and Authors
-------------------

[](#license-and-authors)

- Author: Hubert Jagodziński ()
- Author: Mateusz Gajewski ()
- Author: Sergey P ()
- Author: Christopher Mancini ()

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](License).

References
----------

[](#references)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance12

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 51.7% 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 ~133 days

Total

3

Last Release

3393d ago

Major Versions

v1.0.1 → v2.0.0-alpha2017-02-02

PHP version history (2 changes)v1.0.0PHP &gt;=5.3

v2.0.0-alphaPHP &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/cf74f27d9dc3da65ef59f9654dc4c3f9d3c7fd0b82f330adda0cafa5bda9c0d8?d=identicon)[christophermancini](/maintainers/christophermancini)

---

Top Contributors

[![hjagodzinski](https://avatars.githubusercontent.com/u/3833077?v=4)](https://github.com/hjagodzinski "hjagodzinski (15 commits)")[![cujo](https://avatars.githubusercontent.com/u/398518?v=4)](https://github.com/cujo "cujo (5 commits)")[![nyoung](https://avatars.githubusercontent.com/u/4152009?v=4)](https://github.com/nyoung "nyoung (5 commits)")[![dcelasun](https://avatars.githubusercontent.com/u/144373?v=4)](https://github.com/dcelasun "dcelasun (2 commits)")[![christophermancini](https://avatars.githubusercontent.com/u/131620?v=4)](https://github.com/christophermancini "christophermancini (1 commits)")[![deejay1](https://avatars.githubusercontent.com/u/41211?v=4)](https://github.com/deejay1 "deejay1 (1 commits)")

---

Tags

dataprotocol bufferspb

### Embed Badge

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

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

###  Alternatives

[apache/avro

Apache Avro™ is a data serialization system.

3.2k26.8k3](/packages/apache-avro)[samayo/country-json

A simple but useful data of the world (by country) in JSON formats

1.1k22.4k](/packages/samayo-country-json)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[friendsofcxml/cxml-php

PHP Implementation of cXML Standard

16100.6k2](/packages/friendsofcxml-cxml-php)[honzabrecka/transit-php

Transit for PHP.

1831.0k1](/packages/honzabrecka-transit-php)[crwlr/schema-org

Extract schema.org structured data from HTML documents.

1519.9k1](/packages/crwlr-schema-org)

PHPackages © 2026

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