0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel と MessagePack で遊ぶ

Last updated at Posted at 2021-03-22

動作環境

  • 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'
    );
});

資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?