PHP code example of sqrt-cat / proto-bin

1. Go to this page and download the library: Download sqrt-cat/proto-bin library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sqrt-cat / proto-bin example snippets




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;
    }
}


// 你的业务数据
$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;