Coder Social home page Coder Social logo

php-protobuf's Introduction

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

php-protobuf's People

Contributors

aerror2 avatar alex-d avatar cdddcw avatar cujo avatar dcelasun avatar deejay1 avatar hjagodzinski avatar nyoung avatar serggp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-protobuf's Issues

Problem with nested messages

Hi,

How to use nested messages?
For example i have the following proto:

message Foo
{
    required int32 bar = 1;
    optional string baz = 2;
    repeated float spam = 3;

    message Sub
    {
        optional int64 id = 1;
        optional int32 age_sec = 2;
    }
}

Using protoc-gen-php.php makes two php Files: Foo.php and Foo_Sub.php
And Foo.php has no mention of sub anywhere. How to deal with this?

Can't compile file with own enum type

When I try to compile this enum type and message

enum EJobStatus {
    WAITING = 0;
    RUNNING = 1;
    FINISHED = 2;
};

message MJobs {
    optional string name = 1;
    optional EJobStatus status = 2;
}

I get this error:

php php-protobuf/protoc-php.php MJobs.proto
*Proto file missformed*

Anyone recognize this error (RedHat)

PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20121212/protobuf.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20121212/protobuf.so: undefined symbol: zend_get_hash_value in Unknown on line 0

Integrate with Protobuf-PHP

I'm the author of Protobuf-PHP and I would like to propose you to merge both projects.

To be honest, the main motivation on my part is that I'm no longer doing PHP development, so maintaining the library has become a low-priority task for me. It'll be great if both projects could be merged to offer a great solution for Protobuf under PHP.

About two years ago I integrated a C extension for parsing the protobuf binary format (the lazy branch on the repo), since we needed some additional performance in a project. That change forced some refactorings and several optimizations to the PHP code too. It should be fairly easy to include support for your C extension.

As I see it, both projects have strong points going for them, php-protobuf must be really fast by having the runtime completely implemented in C, while protobuf-php hooks into the protoc command as a plugin to make use of its compiler, can work without extensions and allows to use other formats (ie: json, xml).

What do you think?

Does php-protobuf work with pthreads?

I'm writing a multi-threaded php daemon. I use php-protobuf to de/serialize the data from/to backend processes.The daemon spawned a few workers threads using pthreads extension. When the worker thread is trying to set the value of a php-protobuf-generated-class instance, the program received SEGMENTATION FAULT. The instance is allocated in the worker thread. Here is the stack trace:

[New Thread 0x163f of process 72143]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x163f of process 72143]
0x0000000100802ac7 in _zend_is_inconsistent (ht=0x0, file=0x100decb0c "/Users/zxjcarrot/Softwares/php-5.4.40/Zend/zend_hash.c", 
    line=1017) at Zend/zend_hash.c:54
54      if (ht->inconsistent==HT_OK) {
(gdb) bt
#0  0x0000000100802ac7 in _zend_is_inconsistent (ht=0x0, 
    file=0x100decb0c "/Users/zxjcarrot/Softwares/php-5.4.40/Zend/zend_hash.c", line=1017) at Zend/zend_hash.c:54
#1  0x0000000100805e9e in zend_hash_index_find (ht=0x0, h=1, pData=0x105b802b0) at Zend/zend_hash.c:1017
#2  0x00000001030f2e90 in pb_get_field_descriptor () from /Users/zxjcarrot/Softwares/php-protobuf/modules/protobuf.so
#3  0x00000001030f20be in pb_assign_value () from /Users/zxjcarrot/Softwares/php-protobuf/modules/protobuf.so
#4  0x00000001030f5072 in zim_ProtobufMessage_set () from /Users/zxjcarrot/Softwares/php-protobuf/modules/protobuf.so
#5  0x00000001008346cb in execute_internal (execute_data_ptr=0x105983768, return_value_used=1, tsrm_ls=0x103267380)
    at Zend/zend_execute.c:1480
#6  0x00000001007cfe73 in dtrace_execute_internal (execute_data_ptr=0x105983768, return_value_used=1, tsrm_ls=0x103267380)
    at Zend/zend_dtrace.c:97
#7  0x000000010088ec6c in zend_do_fcall_common_helper_SPEC (execute_data=0x105983768, tsrm_ls=0x103267380)
    at Zend/zend_vm_execute.h:645
#8  0x000000010084e43d in ZEND_DO_FCALL_BY_NAME_SPEC_HANDLER (execute_data=0x105983768, tsrm_ls=0x103267380)
    at Zend/zend_vm_execute.h:756
#9  0x0000000100834ca8 in execute (op_array=0x1059f6438, tsrm_ls=0x103267380) at Zend/zend_vm_execute.h:410
#10 0x00000001007cfc75 in dtrace_execute (op_array=0x1059f6438, tsrm_ls=0x103267380) at Zend/zend_dtrace.c:73
#11 0x000000010088eeaa in zend_do_fcall_common_helper_SPEC (execute_data=0x105982e18, tsrm_ls=0x103267380)
    at Zend/zend_vm_execute.h:673
#12 0x000000010084e43d in ZEND_DO_FCALL_BY_NAME_SPEC_HANDLER (execute_data=0x105982e18, tsrm_ls=0x103267380)
    at Zend/zend_vm_execute.h:756
#13 0x0000000100834ca8 in execute (op_array=0x105c5e5f0, tsrm_ls=0x103267380) at Zend/zend_vm_execute.h:410
#14 0x00000001007cfc75 in dtrace_execute (op_array=0x105c5e5f0, tsrm_ls=0x103267380) at Zend/zend_dtrace.c:73
#15 0x000000010088eeaa in zend_do_fcall_common_helper_SPEC (execute_data=0x1059825f8, tsrm_ls=0x103267380)
    at Zend/zend_vm_execute.h:673
#16 0x000000010084e43d in ZEND_DO_FCALL_BY_NAME_SPEC_HANDLER (execute_data=0x1059825f8, tsrm_ls=0x103267380)
    at Zend/zend_vm_execute.h:756
#17 0x0000000100834ca8 in execute (op_array=0x1059d60b0, tsrm_ls=0x103267380) at Zend/zend_vm_execute.h:410
#18 0x00000001007cfc75 in dtrace_execute (op_array=0x1059d60b0, tsrm_ls=0x103267380) at Zend/zend_dtrace.c:73
#19 0x00000001033a389e in pthreads_routine ()
   from /usr/local/Cellar/php54/5.4.39/lib/php/extensions/debug-zts-20100525/pthreads.so
#20 0x00007fff935a4268 in _pthread_body () from /usr/lib/system/libsystem_pthread.dylib
#21 0x00007fff935a41e5 in _pthread_start () from /usr/lib/system/libsystem_pthread.dylib
#22 0x00007fff935a241d in thread_start () from /usr/lib/system/libsystem_pthread.dylib
#23 0x0000000000000000 in ?? ()
(gdb) p ht
$1 = (const HashTable *) 0x0
(gdb) 

Does php-protobuf work with pthreads?

Issue making extension with phpize

Hi. I just tried using phpize to make the extension and got this error:

"/php-protobuf/protobuf.c:574: error: PHP_FE_END undeclared here (not in a function)"

I've never used phpize before - could you provide the .so file directly? Does this also create a DLL for windows environments?

Tests Failed When Running php-test.php

I have successfully compile/configure the libraries and make changes to php.ini. I tested by running php protoc-php.php test.proto and it created the file pb_proto_test.php.

Next I ran the test file using the following command:-
php run-test.php

However, all 13 test failed. Below are except of the log:

FAILED TEST SUMMARY

Protocol Buffers embedded message parsing [tests/parse_embedded.phpt]
Protocol Buffers parseFromString throws Exception if string is not protobuf-encoded message [tests/parse_error.phpt]
Protocol Buffers repeated field parsing [tests/parse_repeated.phpt]
Protocol Buffers simple field parsing [tests/parse_simple.phpt]
Protocol Buffers repeated field accessors [tests/repeated_field_accessors.phpt]
Protocol Buffers embedded message serialization [tests/serialize_embedded.phpt]
Protocol Buffers serializeToString() throws Exception if required field not set [tests/serialize_error.phpt]
Protocol Buffers repeated field serialization [tests/serialize_repeated.phpt]
Protocol Buffers simple field serialization [tests/serialize_simple.phpt]
Protocol Buffers setting floating-point value [tests/set_float_field.phpt]
Protocol Buffers setting integer value [tests/set_int_field.phpt]
Protocol Buffers setting object value [tests/set_object_value.phpt]

Protocol Buffers setting string value [tests/set_string_field.phpt]

Can someone please advice me what I am doing wrong. Thanks.

Generate php file under PSR-0 Namespace Autoloading convention

Currently protocol file generates a single php file no matter how many messages there are.

Therefore the generated php file is not under PSR-0 Namespace Autoloading, which is a great feature after php 5.3 for conveniently manage php classes.

It would be very programmer-friendly if the generate php files are:

  • under the same folder
  • filename is consistent with class name
  • correspondent (semantically) to a single message of each protocol file.

Windows Binary

Thanks a lot for the library. Any plans for windows support ?

undefined symbol: Z_DELREF_P

when I use this extension on php5.2.17, some error hanpped. It shows like this protobuf.so: undefined symbol: Z_DELREF_P

Add support for map keyword?

1.can you add support for map keyword?
2.can you add support for the convert between json and protobuf?
thank you

Compiler should create multiple class files

When compiling a proto file with mutltiple message items it in, the compiler should create a php class file for each of the message items. Currently it creates one file with all the classes in it. This breaks PSR-0 guildlines and therefor autoloaders will not load the classes.

PHP 7 issue

I clone php 7 branch (https://github.com/serggp/php-protobuf/tree/php7) and make & make install it , protobuf.so file created successfully
When I load extension and run php this error shown

PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/protobuf.so' - /usr/lib64/php/modules/protobuf.so: undefined symbol: Z_TYPE_PP in Unknown on line 0

PHP 7.0.8 (cli) (built: Jun 23 2016 17:01:31) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.8, Copyright (c) 1999-2016, by Zend Technologies

Centos 6

ZTS Support: Error while building protobuf.c: tsrm_ls undeclared

I'm using gentoo linux on a fresh updated version of PHP (didn't have PDO support which I needed for something else).

$ php --version
PHP 5.6.24-pl0-gentoo (cli) (built: Aug  9 2016 01:50:45)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

During make, I am getting:

libtool: compile:  cc -I. -I/home/avenger/whatsapi/php-protobuf -DPHP_ATOM_INC -I/home/avenger/whatsapi/php-protobuf/include -I/home/avenger/whatsapi/php-protobuf/main -I/home/avenger/whatsapi/php-protobuf -I/usr/lib64/php5.6/include/php -I/usr/lib64/php5.6/include/php/main -I/usr/lib64/php5.6/include/php/TSRM -I/usr/lib64/php5.6/include/php/Zend -I/usr/lib64/php5.6/include/php/ext -I/usr/lib64/php5.6/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /home/avenger/whatsapi/php-protobuf/protobuf.c  -fPIC -DPIC -o .libs/protobuf.o
In file included from /usr/lib64/php5.6/include/php/Zend/zend_alloc.h:27:0,
                 from /usr/lib64/php5.6/include/php/Zend/zend.h:252,
                 from /usr/lib64/php5.6/include/php/main/php.h:35,
                 from /home/avenger/whatsapi/php-protobuf/protobuf.c:1:
/home/avenger/whatsapi/php-protobuf/protobuf.c: In function ‘pb_assign_value’:
/usr/lib64/php5.6/include/php/Zend/../TSRM/TSRM.h:167:18: error: ‘tsrm_ls’ undeclared (first use in this function)
 #define TSRMLS_C tsrm_ls
                  ^
/usr/lib64/php5.6/include/php/Zend/../TSRM/TSRM.h:168:21: note: in expansion of macro ‘TSRMLS_C’
 #define TSRMLS_CC , TSRMLS_C
                     ^
/home/avenger/whatsapi/php-protobuf/protobuf.c:24:34: note: in expansion of macro ‘TSRMLS_CC’
  zend_throw_exception_ex(NULL, 0 TSRMLS_CC, "%s: compile error - " #message, Z_OBJCE_P(this)->name, __VA_ARGS__)
                                  ^

What I could find about this missing tsrm_ls is related to PHP with ZTS (zend threads security) enabled and seems that a different approach must be taken while building extensions to PHP using it. To enable ZTS on php, the --enable-maintainer-zts flag should be used.

PHP manual page for this setting: http://php.net/manual/en/internals2.buildsys.environment.php

I'm not sure which gentoo USE flag enabled this in my PHP set up, but I could successfully build and install other extension (https://github.com/mgp25/curve25519-php) with no problem.

I could find some projects that required slight changes in the source files in order to be able to. To name some: phpredis/phpredis#193 and libgeos/geos#9.

I'll try to investigate more on this (for a solution) when I have more time but, if the investigation above helps someone willing to jump in, please don't hesitate!

Unable to phpize in windows

This module easily got phpized in linux and gave .so, but phpizing in windows is not happening. Can you provide dll for it?

Add support for PHP7?

The five RC of PHP has been released, and PHP 7 is likely to be released on Nov 12 this year.

Add full support for maps

A map field is currently represented as an array of MapFieldEntry objects instead of simply array of keys and values. This kind of behavior is described in a greater detail in the official documentation in the Backwards compatibility.

Syntax error required uint32 Time=1;

message Log{
    required uint32 Time=1;
    message Content{
        required string Key=1;
        required string Value=2;
    }
    repeated Content Contents=2;
}
message LogGroup{
    repeated Log Logs=1;
    required string Category=2;
    optional string Topic=3;
    optional string Source=4;
}

don't know why it throw the error..

the count problem

why when the message like this
message A {
required int32 count =1;
}
the php class file has the error like this
not be compatible with ProtobufMessage::getCount($position)。

thank you.

使用protobuf中extensions问题

extensions 100 to 1000;在proto文件中加入extensions ,在生成php文件的时候会报位置的类型错误,java中的proto可以用extensions 字段,请问php中如何使用

PHP Notice when trying to compile a proto file and failure when creating output PHP file

I get the following "PHP Notice" when trying to compile a proto file ( from Google tutorial https://developers.google.com/protocol-buffers/docs/pythontutorial). I can't see output PHP file from parser after parsing addressbook.proto.

Below I publish my steps and error message from PHP:

user@bieli:php-protobuf/example$ cat > addressbook.proto
package tutorial;

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}

^Z
[2]+  Stopped                 cat > addressbook.proto
user@bieli:php-protobuf/example$ php ../protoc-php.php addressbook.proto 
PHP Notice:  Undefined index: PhoneType in php-protobuf/ProtobufCompiler/ProtobufParser.php on line 1039
Type PhoneType not defined

My general problem it's failure output PHP file.

For comparision, when I using Google tools for Python ( https://developers.google.com/protocol-buffers/docs/pythontutorial ) I can see output file, after default 'protoc' command:

user@bieli:php-protobuf$ protoc --proto_path=./ --python_out=/tmp/ example/addressbook.proto

user@bieli:php-protobuf$ file /tmp/example/addressbook_pb2.py 
/tmp/example/addressbook_pb2.py: Python script, ASCII text executable, with very long lines

In Python code I can see important section:

_PERSON_PHONETYPE = descriptor.EnumDescriptor(
  name='PhoneType',
  full_name='tutorial.Person.PhoneType',
  filename=None,
  file=DESCRIPTOR,
  values=[
    descriptor.EnumValueDescriptor(
      name='MOBILE', index=0, number=0,
      options=None,
      type=None),
    descriptor.EnumValueDescriptor(
      name='HOME', index=1, number=1,
      options=None,
      type=None),
    descriptor.EnumValueDescriptor(
      name='WORK', index=2, number=2,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=215,
  serialized_end=258,
)

I know workaround for this problem by extracting enum from message:

package tutorial;


enum PhoneType {
  MOBILE = 0;
  HOME = 1;
  WORK = 2;
}

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}

but maybe my issue is important for refactoring *.proto parser in PHP.

Good luck

Bug fixes for empty comments, and nested message definitions

First of all: Thanks a lot for the library. It is absolutely awesome! I've been using an adapted version of pb4php before, and it was quite slow. With the compiled PHP extension, php-protobuf is like three times as fast, which is really great.

I've found two small glitches with the PHP-protobuf compiler:

  1. Empty single-line comments where not removed correctly. I fixed that here:
    danielmewes/php-rql@fddfc7e
  2. If a message had more than one nested message types, the latter ones were not declared correctly. Fixed here:
    danielmewes/php-rql@2c5b67e
  3. I have to support PHP 5.3 in my project, so I replaced a macro to make it compile:
    danielmewes/php-rql@6754474

How to change a value in a repeated item

1 message UserItem
2 {
3 repeated int32 nums = 1;
4 }
5
6 message User
7 {
8 repeated int32 data = 1;
9 optional UserItem item = 2;
10 }

for example,

12 include('pb_proto_test.php');
13
14 $u = new User();
15
16 for($i=0; $i<2; $i++ )
17 {
18 $u->appendData($i);
19 }
20 echo $u->getDataAt(1)."\n"; // 0
21 echo $u->getDataAt(0)."\n"; // 1

34 $d = $u->getDataIterator();

36 $d->offsetSet(1, 100); // want to change data[1] = 100;
37 var_dump($d); // d is object, has array( 0=>0, 1=>100)
39 var_dump($u->getData()); // but u has not been changed?

if I want to change a item's value in a repeated field, what should i do?

Can't find generated file

When running command:

php protoc-php.php MyFile.proto

it runs and does nothing. Where the files are being generated?

Resolve imports dependency paths?

I am attempting to compile some .proto files for a large project our company is working on and many of their .proto files have large numbers of import statements which refer to other .proto files outside the current directory.

The drslump library looks like it has a -i statement which allows you to tell protoc to look in other directories for dependent files.

I called protoc-php.php with no options and this is what it said:

USAGE: protoc-php.php [OPTIONS] PROTO_FILE
-n, --use-namespaces Use native PHP namespaces
-p, --filename-prefix [PREFIX] Specify a prefix for generated file names
--psr Output class files in a psr-4 directory structure

Problem with recursive types

The compiler cannot handle when a type has a member of its own type, thus it's impossible to represent nested (tree-like) structures, while Protocol Buffers allow this.

Error message:

PHP Notice:  Undefined index: XXX in /path/to/php-protobuf/ProtobufCompiler/ProtobufParser.php
Type XXX not defined

Relevant excerpt from proto file:

message XXX {
    optional uint32 somedata = 1;
    repeated XXX children = 2;
}

How to install php-protobuf in xamp (Window) .

Hi please help me i want to install php-protobuf in xamp on window.but i have no idea how it will be installed .when i run protoc-php.php its show "requires protobuf extension installed to run". how can i install this extension ??

Thanks

Not working in windows 10

Hi, the dll compiled is not working in windows 10. Its running fine in windows 7. Anyone have this problem?

Empty objects

In this proto

message MyProto {
    User user = 1;
    float id = 2;
}

If I create new object of MyProto and set user and empty User object , when I printDebugString , Ican see empty object in user property
But if I serializeToString and parseFromString and then printDebugString , there is no empty object and user is null
Why? How can I pass empty object ?

How to composer require ?

How can I require allegro/php-protobuf using composer?

In composer.json

{
    "require": {
        "pear/console_commandline": "^1.2"
    }
}

there is no package name

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.