Ubuntu 安装Protobuf-php步骤

git clone https://github.com/allegro/php-protobuf.git   php-protobuf

cd php-protobuf/

phpize

make

make instal

找到php.in,加入这行代码:extension=/usr/lib64/php/modules/protobuf.so 重启服务器,使用phpinfo()查看是否已经安装拓展

新建一个简单的proto文件:

vim test.proto



输入以下内容:

message PhoneNumber {

    required string number = 1;

    required int32 type = 2;

  }


message Person {

      required string name = 1;

      required int32 id = 2;

      optional string email = 3;

      repeated PhoneNumber phone = 4;

      optional double money = 5;

}


message AddressBook {

  repeated Person person = 1;

}



编译。注意,这里需要引用到protoc-php.php这个文件,注意路径。

php ./php-protobuf-master/protoc-php.php  test.proto



编译成功后会在当前目录生成一个pbprototest.php文件

如果ls没有显示文件,可能是隐藏文件 使用ls -a

这里会继承ProtobufMessage类,它是在protobuf.so中自动加载的。 写一个测试类来测试一下:

<?php

require_once 'pb_proto_test.php';


$foo = new Person();

$foo->setName('hellojammy');

$foo->setId(2);

$foo->setEmail('[email protected]');

$foo->setMoney(1988894.995);


$phone_num = new PhoneNumber();

$phone_num->setNumber('1351010xxxx');

$phone_num->setType(3);


$foo->appendPhone($phone_num);

//$foo->appendPhone(2);

$packed = $foo->serializeToString();

//echo $packed;exit;

#$foo->clear();

echo "-----------src------------\n";

echo $foo->getName() ."\n";

echo $foo->getPhone()[0]->getNumber() ."\n";

$foo->dump();

echo "------------------------\n\n\n";



try {

      $p = new Person();

      $p->parseFromString($packed);

      echo "------------parsed-------\n";

      echo $p->getName() ."\n";

      echo $p->getEmail() ."\n";

      echo $p->getMoney() ."\n";

      echo $p->getId() . "\n";

      echo $p->getPhone()[0]->getNumber() ."\n";


      //$p->dump();

      echo "------------------------\n";

      //print_r($xiao);

      } catch (Exception $ex) {

      die('Upss.. there is a bug in this example');

}



运行

php text.php



可以看到输出:

-----------src------------

hellojammy

1351010xxxx

Person {

  1: name => 'hellojammy'

  2: id => 2

  3: email => '[email protected]'

  4: phone(1) =>

    [0] =>

      PhoneNumber {

        1: number => '1351010xxxx'

        2: type => 3

      }

  5: money => 1988894.995

}

------------------------



------------parsed-------

hellojammy


1988894.995

2

1351010xxxx

------------------------




假如出现提示../php-protobuf/protoc-php.php requires protobuf extension installed to run


/alidata/server/php/bin/php

为了了解protobuf的压缩原理,我特意安装了protobuf-c





这两个size是4和15,最后一位是结束符

如果用protobuf序列化后,总长度是18

节省了一个结束符,排列更加紧密

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章