sqrt-cat/proto-bin

A PHP library similar to protobuf for binary protocol packaging/unpacking, which can package biz data into binary format for efficient transmission. Implemented using native PHP with no other external dependencies. Supports data types such as fixed length and variable length.

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/sqrt-cat/proto-bin

v1.0.0 2025-05-12 08:44 UTC

This package is auto-updated.

Last update: 2025-12-12 10:10:27 UTC


README

ProtoBin 是一个使用PHP原生开发的二进制协议的序列化库。在 PHP 前提下,理念与 Protobuf 类似,但更加简单易用。

支持数据类型

定长类

const TYPE_TINYINT = 'tinyint'; const TYPE_INT16 = 'int16'; const TYPE_INT32 = 'int32'; const TYPE_INT64 = 'int64';

变长类

const TYPE_STRING = 'string'; const TYPE_TEXT = 'text';

你可能会吐槽为何没有非标量数据类型,其实可以序列化后用text类型来存储。

示例代码

# 安装依赖
composer require sqrt-cat/proto-bin

消息体定义

<?php
use SqrtCat\ProtoBin\ProtocolMessage;
use SqrtCat\ProtoBin\ProtocolType;

class RegisterRequest extends ProtocolMessage
{
    public $account;
    public $password;
    public $age;

    // 参数项位序 accountBin passwordBin ageBin
    public static $paramNameMapping = [
        0 => 'account',
        1 => 'password',
        2 => 'age',
    ];

    // 参数类型
    public static $paramProtocolTypeMapping = [
        'account'  => ProtocolType::TYPE_STRING,
        'password' => ProtocolType::TYPE_STRING,
        'age'      => ProtocolType::TYPE_TINYINT,
    ];

    public function setAccount($account)
    {
        $paramType        = static::getParamType('account');
        $this->accountBin = ProtocolType::pack($account, $paramType);
    }

    public function getAccount()
    {
        return $this->account;
    }

    public function setPassword($password)
    {
        $paramType         = static::getParamType('password');
        $this->passwordBin = ProtocolType::pack($password, $paramType);
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setAge($age)
    {
        $paramType    = static::getParamType('age');
        $this->ageBin = ProtocolType::pack($age, $paramType);
    }

    public function getAge()
    {
        return $this->age;
    }
}

打包/解包业务数据

<?php
// 你的业务数据
$data = [
    'account'  => 'sqrtcat',
    'password' => '123456',
    'age'      => 29,
];

var_dump(http_build_query($data));// 文本表单模式的数据字节数
var_dump(json_encode($data));// 文本json模式的数据字节数

// 二进制协议打包
$registerRequest = new RegisterRequest();
$registerRequest->setAccount('sqrtcat');
$registerRequest->setPassword('123456');
$registerRequest->setAge(29);
$dataBin = $registerRequest->packToBinStream();
var_dump($dataBin);// 二进制协议数据字节数

// 解包二进制协议
$registerRequest->unpackFromBinStream($dataBin);
echo $registerRequest->getAccount() . PHP_EOL;
echo $registerRequest->getPassword() . PHP_EOL;
echo $registerRequest->getAge() . PHP_EOL;

对比二进制的传输协议与表单、文本类协议的字节数,可以发现二进制协议的传输效率更高。