動作環境
- Mac OS X 10.15.7
- Laravel 7.x|8.x
- rybakit/msgpack 0.8
- msgpack-tools 0.6
プロジェクトの作成
composer require rybakit/msgpack
レスポンスの作成
routes/web.php
use MessagePack\Packer;
Route::get('/example.mp', function () {
$value = (new Packer())->pack([
'id' => 1,
'name' => 'John Doe',
'age' => 18,
]);
return response($value)->header('Content-Type', 'application/x-msgpack');
});
ターミナルで確認
brew install msgpack-tools
php artisan serve
curl http://localhost:8000/example.mp | msgpack2json -d
レスポンスマクロの作成
php artisan make:provider MessagePackResponseServiceProvider
app/Providers/MessagePackResponseServiceProvider.php
namespace App\Providers;
use MessagePack\Packer;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;
class MessagePackResponseServiceProvider extends ServiceProvider
{
public function boot()
{
Response::macro('mpac', function ($value) {
return response((new Packer())->pack($value))->header(
'Content-Type',
'application/x-msgpack'
);
});
}
}
config/auth.php
return [
'providers' => [
# ...
App\Providers\MessagePackResponseServiceProvider::class,
],
];
routes/web.php
Route::get('/example.mp', function () {
return response()->mpac([
'id' => 1,
'name' => 'John Doe',
'age' => 20,
]);
});
ターミナルで確認
curl http://localhost:8000/example.mp | msgpack2json -d
Model を渡せるようにする
toArray()
があれば変換しておくと Eloquent Model もそのまま渡せる。
Response::macro('mpac', function ($value) {
if (method_exists($value, 'toArray')) {
$value = $value->toArray();
}
return response((new Packer())->pack($value))->header(
'Content-Type',
'application/x-msgpack'
);
});