PHP使用protobuf步驟

參考文檔/博文:http://yueqian.sinaapp.com/a/52.htmlphp

用的是2.5的protobuf,下載地址:https://github.com/google/protobuf,個人博客文件裏面也有html

系統:linuxlinux

1.二話不說先解壓文件git

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

 

2.看一下安裝成功沒有github

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

 

3.添加環境變量app

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.該安裝的都已經裝好了,而後寫一個protobufui

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命令自定義編譯目錄進行編譯this

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部google

 

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

 

完成

相關文章
相關標籤/搜索