|
| 1 | +# msgpack-php-micro |
| 2 | +msgpack - A super-lightweight PHP implementation of the [msgpack](http://msgpack.org/) data encoding format. |
| 3 | + |
| 4 | +This is a very simple, small PHP implementation of msgpack, for ease of embedding. |
| 5 | + |
| 6 | +Notice: This implementation is still fairly new, and may have bugs. If you find any bugs, please report them immediately, and I will try to get them fixed as soon as possible. |
| 7 | + |
| 8 | +**Usage:** |
| 9 | + |
| 10 | +``` |
| 11 | +require_once('msgpack.php'); |
| 12 | +
|
| 13 | +$data = array( |
| 14 | + 'hello' => 'world', |
| 15 | + 'array' => array(1, 2, 3, 4), |
| 16 | + 5 => 78.662, |
| 17 | + 'dt' => new DateTime(), // DateTime encoded in Timestamp extension format |
| 18 | +); |
| 19 | +
|
| 20 | +$encoded = MsgPack::encode($data); |
| 21 | +
|
| 22 | +$decoded = MsgPack::decode($encoded); |
| 23 | +
|
| 24 | +var_dump($decoded); |
| 25 | +``` |
| 26 | + |
| 27 | +Fully supports custom type extensions: |
| 28 | +``` |
| 29 | +require_once('msgpack.php'); |
| 30 | +
|
| 31 | +class Vertex { |
| 32 | + public $x; |
| 33 | + public $y; |
| 34 | + public $z; |
| 35 | +
|
| 36 | + public function __construct($x=0, $y=0, $z=0) { |
| 37 | + $this->x = floatval($x); |
| 38 | + $this->y = floatval($y); |
| 39 | + $this->z = floatval($z); |
| 40 | + } |
| 41 | +} |
| 42 | +
|
| 43 | +MsgPack::extend(array( |
| 44 | + 'type' => 1, |
| 45 | +
|
| 46 | + 'varType' => 'object', |
| 47 | +
|
| 48 | + 'encode' => function($obj) { |
| 49 | + // returning FALSE skips; see reference for details |
| 50 | + if(!($obj instanceof Vertex)) return FALSE; |
| 51 | +
|
| 52 | + return pack('GGG',$obj->x, $obj->y, $obj->z); |
| 53 | + }, |
| 54 | +
|
| 55 | + 'decode' => function($data) { |
| 56 | + $xyz = unpack('Gx/Gy/Gz',$data); |
| 57 | + return new Vertex($xyz['x'], $xyz['y'], $xyz['z']); |
| 58 | + }, |
| 59 | +)); |
| 60 | +``` |
| 61 | + |
| 62 | +Visit [github.com/CodeSmith32/msgpack-php-micro](https://github.com/CodeSmith32/msgpack-php-micro) for the usage reference. |
0 commit comments