PHP使用Protobuf
[scode type="share"]Protobuf是一种数据格式转换中间件,主要解决数据格式不一致的问题,这种问题可能出现在不同语言之间,也有可能出现在不同接口之间。[/scode]
一、特性:
1、统一格式
2、对数据进行不完全压缩
二、环境配置及使用(PHP版本:php5.6)
1、下载并安装protoc编译器(protoc是用来根据.proto文件生成对应php的可执行文件)
cd /usr/local/src
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.1.0/protobuf-php-3.1.0.zip
unzip protobuf-php-3.1.0.zip
cd protobuf-php-3.1.0
./configure --prefix=/usr/local/proto3.1
make
make install
ln -s /usr/local/proto3.1/bin/protoc /usr/bin/protoc
2、下载并安装protoc对应的php扩展
cd /usr/local/src
wget --no-check-certificate https://github.com/chobie/php-protocolbuffers/archive/master.zip
unzip master
cd php-protocolbuffers-master/
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/bin/php-config
make
make install
3、重启环境(php-fpm或者http服务)
4、下载protoc-gen-php插件,配合protoc来生成php代码
cd /var/www/plugin
git clone https://github.com/drslump/Protobuf-PHP.git
path/php56/bin/pear channel-discover pear.pollinimini.net
path/php56/bin/pear install drslump/Protobuf-beta
5、根据.proto结构文件生成对应的php操作代码
protoc --proto_path=/var/www/html/webroot --php_out=/var/www/html/webroot/helloworld --plugin=protoc-gen-php=/var/www/html/php-protobuf/protoc-gen-php.php /var/www/html/webroot/helloworld.proto
6、在项目根目录下配置/var/www/html/webroot/composer.json文件,并将helloworld目录设置为autoload目录
{
"name": "protobuf",
"description": "protobuf example for PHP",
"require": {
"google/protobuf": "^v3.3.0"
},
"autoload": {
"psr-4": {
"helloworld\\": "helloworld/"
}
}
}
下载vendor目录,安装composer见这里《Composer下载安装》
composer install
7、PHP使用Protobuf示例
创建test.php文件,内容如下
<?php
require dirname(__FILE__). '/../../vendor/autoload.php';
require dirname(__FILE__). '/../../helloworld/helloworld.pb.php';
$HelloRequest = new \Helloworld\HelloRequest();
$HelloRequest->setName('zhangsan');
$HelloRequest->setAge(28);
$packed = $HelloRequest->serializeToString();
try {
// clinet端可以仿照这块的逻辑解析并使用具体数据
$HelloRequest = new \Helloworld\HelloRequest();
$HelloRequest->mergeFromString($packed);
var_dump($HelloRequest->getAge());exit;
}
catch (Exception $ex) {
die('Error: ' . $ex->getMessage());
}
三、一些想法
前后端数据传输方式:
1、server端
a. server端生成.proto结构文件
b. 接口数据根据.proto结构序列化数据
c. 通过http返回给clinet端
2、client端
a. client端拿到序列化的数据
b. 通过根据.proto文件生成的类将拿到的序列化后的字符串进行解码
c. 之后通过类文件 Class->getName() 的方式获取具体的数据
至于.proto文件可用通过统一的接口进行前后端传输
a. 打包时候包含这些.proto
b. 每过N时间更新N时间内有变更的.proto文件
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭