allegro/php-protobuf

Problem with nested messages

swapniel99 opened this issue · 9 comments

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?

There is no mention about this class because it's not needed 😉 What's the exact issue you're dealing with?

How to deserialize such a message, can you please give an example?

Take a look at Usage.

Your hints and clues won't work because I am not a PHP programmer. Usage doesn't show the nested case I am asking about.

Please tell me how to create such a PHP object and serialize it. How to deserialize it. How to include multiple php files generated.

The only difference the nested case implies is different class name, nothing more. Please find an example for your case but it doesn't show much more than the Usage section.

require_once 'Foo_Sub.php';

$fooSub = new \Foo_Sub();
$fooSub->setId(1);
$fooSub->setAgeSec(2);
$packed = $fooSub->serializeToString();

$unpackedSubFoo = new \Foo_Sub();
$unpackedSubFoo->parseFromString($packed);
$unpackedSubFoo->dump();

This I was able to do before. But don't we need to add $fooSub to $foo somehow? Like shouldn't there be addSub function in Foo?
So that we get a single packed string. When I receive a packed string how do i differentiate?

You don't have a field of type Sub in Foo message..

Yes.. But shouldn't there be? The example you gave simply deals with Foo_Sub.
Not the entire Foo. How to do that?

No, you don't need to define a field of nested type, it's up to you but basically you define nested messages to use them in a parent message.