ハマログ

株式会社イーツー・インフォの社員ブログ

PHPでMessagePackを利用する

はじめに

PHPでMessagePackを利用してみます。

MessagePackとは

公式サイトはこちら https://msgpack.org/
日本語 https://msgpack.org/ja.html

MessagePackは、オブジェクトをシリアライズするためのフォーマットで、メッセージをバイナリ形式で扱います。

以下、公式サイトより。JSONだと27bytesのデータが18bytesで扱えるようです。

やってみよう

公式サイトではPECLで導入するって書いてあるけどめんどくさいのでcomposerでいれたい。
# composer search msgpack

rybakit/msgpack A pure PHP implementation of the MessagePack serialization format.
apix/cache A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache taggging and indexing to Redis, Memcached, PDO/SQL, APC and other adapters.
lvht/msgpack-rpc
wyrihaximus/msgpack ext-msgpack polyfill using rybakit/msgpack
ltd-beget/msgpackrpc Port of PEAR MessagePack RPC Client to PHP 5.3+
hannesvdvreken/msgpack Msgpack implementation for PHP. It's like JSON. But fast and small.
gilek/php-msgpack-stubs
bezier/msgpack-php MessagePack with pure PHP fail over
guancheng/msgpack The lumen api response wrapper for rybakit/msgpack.
epokmedia/msgpackrpc Port of PEAR MessagePack RPC Client to PHP 5.3+
alexmasterov/msgpack A pure and efficient MessagePack serialization library
wyrihaximus/react-cache-msgpack MessagePack encode/decode decorator for react/cache
titaniumcodes/middleware-msgpack PSR-7 Middleware of msgpack.org
funeralzone/msg-pack-php This package tries to leverage the power of Message Pack and msgpack.php. Mainly this uses https://github.com/msgpack-rpc/msgpack-rpc-php while updating the underlying code & upgrading to the above mentioned msgpack.php package.
aliance/compressor Pack and compress value to shorten string.
結構でてきた。 今回は、GitHubの更新日が近かったためrybakit/msgpackを選択
# composer require rybakit/msgpack
Using version ^0.5.3 for rybakit/msgpack
# 以下略
導入できたのでコードを書いてみます。
use MessagePack\MessagePack;

// 略

$pack = [
        'compact' => true,
        'schema' => 0
];

$packed = MessagePack::pack($pack);
var_dump($packed);
結果
string(18) "��compactæschema"
バイナリなので一部読めないけどよさそう。
もとに戻してみる
// 上記のコードに続いて

$unpacked = MessagePack::unpack($packed);
var_dump($unpacked);
結果
array(2) { ["compact"]=> bool(true) ["schema"]=> int(0) }
大丈夫そう
公式サイトにあるとおりかどうか、容量を比較してみる
$pack = [
    'compact' => true,
    'schema' => 0
];

$json = json_encode($pack);
$size = mb_strlen($json, '8bit');
var_dump($size);

$packed = MessagePack::pack($pack);
$size = mb_strlen($packed, '8bit');
var_dump($size);
結果
int(27) int(18)
バッチリ
ということで、いまさら感ちょっとありますが、PHP+MessagePackを試してみました。

以上。
JSONMessagePackMsgPackPHPseralizeシリアライズ

  kaneko tomo   2018年8月20日


関連記事

マクド

奄美にはマクドナルドがありません。 関東ではマック、関西ではマクドって言いますけ…

Laravel5のartisanコマンドの自作

Laravel5でArtisanコマンドを自作する方法について。 Laravel…

Amazon Linux2でLocaleを変更してみた

  はじめに どうも!T-utsuです。 最近なにかとAWSをいじるこ…


← 前の投稿

次の投稿 →