PHP使用protobuf步骤

参考文档/博文:http://yueqian.sinaapp.com/a/52.html

用的是2.5的protobuf,下载地址:https://github.com/google/protobuf,我的博客文件里面也有

系统:linux

1.二话不说先解压文件

tar -xvzf protobuf-2.5.0.tar.gz
cd protobuf-2.5.0
./configure --prefix=/usr/local/protobuf
make && make install

 

2.看一下安装成功没有

/usr/local/protobuf/bin/protoc --version
>>libprotoc 2.5.0

 

3.添加环境变量

export PATH=$PATH:/usr/local/protobuf/bin

  

4.protobuf转php文件需要下载另外一个库protoc-gen-php

git clone https://github.com/drslump/Protobuf-PHP.git
cd Protobuf-PHP/
./protoc-gen-php.php --help

  

5.该安装的都已经装好了,然后写一个protobuf

package protos;
message Comment {
  required uint64 id = 201;
  required string text = 202;
  optional uint64 created_at = 203;
}

 

6.由于protoc-gen-php预设了编译目录,所以编译时需要转移到编译目录(Protobuf-PHP/library/DrSlump/Protobuf/Compiler/protos)。也可以直接使用protoc命令自定义编译目录进行编译

protoc \
--plugin=protoc-gen-php='/data/wwwroot/gameall.sdsfshop.com/Protobuf-PHP/protoc-gen-php.php' \
--proto_path='/data/wwwroot/gameall.sdsfshop.com/Protobuf-PHP/newProto/' \
--php_out=':./' \
'/data/wwwroot/gameall.sdsfshop.com/Protobuf-PHP/newProto/Edifice.proto'

 

成功的话会在newProto下生成一个Edifice.php的文件,中间报了个致命错误..发现是pear有问题,看第7步,没问题可以跳过第7部

 

7.这时候你可能会报错,说没办法引用文件,这是你的PEAR还没设置好路径,我的pear是装在/usr/local/php5/bin这里,执行一下代码

/usr/local/php5/bin/pear channel-discover pear.pollinimini.net
/usr/local/php5/bin/pear install drslump/Protobuf-beta

  

8.然后再执行一下步骤6

9.写一个测试demo

include_once dirname(__FILE__).'/library/DrSlump/Protobuf.php';
\DrSlump\Protobuf::autoload();
include_once dirname(__FILE__).'/comment.php';
$comment = new protos\Comment;
$comment->setId(1);
$comment->setText('this is a test');
//use default codec
$data = $comment->serialize();
//use custom codec
$codec = new \DrSlump\Protobuf\Codec\Binary();
$data = $codec->encode($comment);
//decode
$comment_dec = new protos\Comment;
var_dump($codec->decode($comment_dec, $data));

 

完成

posted @ 2017-09-22 09:28  MauriceChans  阅读(1832)  评论(0编辑  收藏  举报