Install php-protobu extension and use

Source: Internet
Author: User
Install php-protobu extensions for php and use resources: https://github.com/allegro/php-protobuf/

Go to the extract directory and run phpize.

./Configure

Make

Make install

# Please add following line to your php. ini

Extension = protobuf. so

Restart PHP


Phpinfo () shows the protobuff extension.



How to use it?

Save

First, the proto file foo. proto file is created.


Message PhoneNumber {

Required string number = 1;

Required int32 type = 2;

}

Message Person {

Required string name = 1;

Required int32 id = 2;

Optional string email = 3;

Repeated PhoneNumber phone = 4;

}

Message AddressBook {

Repeated Person person = 1;

}

Then generate

Php protoc-php.php foo. proto

At this time, a pb_proto_foo.php file will be generated.


The specific application is as follows.


For example, to communicate with JAVA. Protobuffer stores the php file test. php, for example:

Require_once 'pb _ proto_test.php ';

$ Packed = curlGet ('http: // 10.0.247.113: 8080/testweb/proto'); // buffer information returned by JAVA

$ Foo = new AddressBook ();

Try {

$ Foo-> parseFromString ($ packed );

} Catch (Exception $ ex ){

Die ('parse error: '. $ e-> getMessage ());

}

$ Pb = $ foo-> getPerson ();

// Print_r ($ pb );

// Print_r ($ pb [0]);

Echo $ pb [0]-> getName (). '_'. $ pb [0]-> getId ().'_';

Print_r ($ pb [0]-> getPhone ());


PHP calls to modify buffer data

----------------------------

Require_once 'pb _ proto_test.php ';

$ Foo = new Person ();

$ Foo-> setName ('xiaoyun ');

$ Foo-> setId (200 );

$ Foo-> setEmail ('dofound @ 163.com ');

// $ Foo-> appendPhone (2 );

$ Packed = $ foo-> serializeToString ();

$ Foo-> clear ();

Try {

$ Xiao = $ foo-> parseFromString ($ packed );

// Print_r ($ xiao );

} Catch (Exception $ ex ){

Die ('upss .. there is a bug in this example ');

}

Echo $ foo-> getName ();

Echo $ foo-> getPhone ()-> number;

$ Foo-> dump ();


PHP internal call

------------------------------

Generate buffer data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.