[TOC]
## 安裝protoc編譯器
> 根據xx.proto文件生成php類,需要用到protoc編譯器 (一般開發環境可以安裝,生產環境可以不用)
> Google's protoc compiler version 2.6 or above
~~~
wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz
tar zxvf protobuf-2.6.1.tar.gz
cd protobuf-2.6.1/
./configure --prefix=/usr/local/protobuf
make && make install
export PATH=/usr/local/protobuf/bin:$PATH
protoc --version
~~~
## 安裝php protobuf 擴展
> 下載地址 https://github.com/allegro/php-protobuf/archive/master.zip
~~~
phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install
~~~
## php.ini 尾部中增加protobuf擴展
~~~
extension = protobuf.so
~~~
## 創建pb測試文件
> 文件名:test.proto
> 頭部需指定是proto2還是proto3,有些第三方提供的是沒有包含,需要顯示指定
~~~
syntax = "proto2";
//syntax = "proto3";
package myapi;
// 字段都是用1,2,3這樣的方式進行索引標識,等轉換成PHP的類的時候,通過getXXFiled()的時候,則是根據這個索引標識進行獲取
message Person {
required int32 id = 1;
required string name = 2;
optional string email = 3;
optional double money = 4;
optional bool is_rich = 5;
}
message player_login
{
optional int32 user_id = 1;
optional string token = 2;
};
~~~
## 生成pb對應的 PHP類文件
~~~
php ./php-protobuf-master/protoc-gen-php.php test.proto
~~~
## hyperf中引用生成類
> /config/container.php
~~~
//自動加載protobuf文件
foreach (glob(BASE_PATH . '/app/Protobuf/Myapi/*.php') as $proto_file) {
require_once($proto_file);
}
~~~
## TestController里進行測試
~~~
public function index()
{
$person = new Person();
$person->setName('www');
$person->setEmail('ww@qq.com');
$person->setId(11);
//$person->setMoney(123.2);
$packed = $person->serializeToString(); // 將對象序列化為字符串
var_dump($person);
var_dump($packed);
echo '--------parse---------'.PHP_EOL;
$p = new Person();
$p->parseFromString($packed); // 解析字符串轉化為對象
var_dump($p);
}
~~~