allegro / php-protobuf

PHP Protobuf - Google's Protocol Buffers for PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get the field type?

alanyao80 opened this issue · comments

commented

I would like to wirte a common encode function that can change the PHP Array to the brotobuf object .
As i knew , the repeated type must set like this:

$object->setmethod(Array $repeatedObject);

How can i get the field type like the "repeated" ?

#user.proto

message Log{
    string action = 1; 
    string time = 2; 
}
message UserInfo{
    string name = 1; 
    repeated Log log = 2;      //how to get "repeated" type in php? 
}

#test.php

$data = [
            'name'=>'alan',
            'logs'=>[            // use repeated type to encode
                ['action'=>'add','time'=>'20170910'],
                ['action'=>'update','time'=>'20170911']
            ]
];
$encodeStr  = encode($fromObject,$data);

In case you have not found the solution yet. Take a look at what public method fields() returns. There you will find information you need. Keep in mind it's internal representation that's subject to change in future (no plans to do so at this moment).

You actually don't need the internal type information. You can simply use a reflection PHP supports (http://php.net/manual/en/class.reflectionclass.php). You can recognise a repeated field by existence of appendLog method in your particular case. You can determine wether a method parameter type is a class and it's name by calling http://php.net/manual/en/reflectionparameter.getclass.php.

commented

Thank you!
I got it;