Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write protobuf3 by PHP

Shulou Source: shulou.com Published: 2022-06-03 15:51:10 10月06日 Update

This article will explain in detail how to read and write protobuf3 in PHP, Xiaobian thinks it is quite practical, so share it with you as a reference, I hope you can gain something after reading this article.

Protobuf(Google Protocol Buffers) is a tool library provided by Google with efficient protocol data exchange formats (similar to Json), but compared to Json, Protobuf has higher conversion efficiency, time efficiency and space efficiency are 3-5 times that of JSON.

In proto3, PHP code can be generated directly using the protoc command. The generated PHP code cannot be used directly, and PHP library support for Protobuf is required.

Here is an example of how PHP can use protobuf. First define the proto file:

syntax = "proto3";package lm;message helloworld{ int32 id = 1; // ID string str = 2; // str int32 opt = 3; // optional field}

Note that the syntax used here is proto3, which is not the same as proto2. The required and optional qualifications are no longer available. All fields are optional.

Then use protoc to generate PHP files:

protoc --php_out=./ hello.proto

You will see that a hello.pb.php file is generated:

namespace Lm;use Google\Protobuf\Internal\DescriptorPool;use Google\Protobuf\Internal\GPBType;use Google\Protobuf\Internal\RepeatedField;use Google\Protobuf\Internal\GPBUtil;class helloworld extends \Google\Protobuf\Internal\Message{ ....}

Read the code below and find that it uses the classes under Google\Protobuf. This is a PHP library that can be downloaded:

https://github.com/google/protobuf/tree/master/php/src/Google/Protobuf

You can also use composer to introduce into the project, it is recommended to use composer to introduce, because composer will help you automatically generate Autoloader:

composer require google/protobuf

When google/protobuf is introduced as a composer, a vendor directory appears in the project. Autoload.php under includevender in your own code, as well as the helloworld.pb.php file just generated, you can read and write binary.

About "PHP how to read and write protobuf3" This article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

Tags: Generation code files efficiency articles more projects good practical binary examples content commands fields tools data articles methods time formats Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Huawei MySQL Docker MariaDB