LoginSignup
1
3

More than 3 years have passed since last update.

PHPでオブジェクトをシリアライズする

Last updated at Posted at 2019-07-09

serializeを使ってSerialization of 'Closure' is not allowedになった場合はOpis Closureを使ってみると良さそう。
super_closureというのもある。

Opis Closure

composer require --dev opis/closure
use function Opis\Closure\{serialize as opisSerialize, unserialize as opisUnserialize};
$path = 'tests/fixtures/serialize/objectName';

// 保存
$file = new \SplFileObject(base_path($path), 'w');
$file->fwrite(encrypt(opisSerialize($objectName))));// encrypt、base_pathはlaravelのもの
// 復元
$object = opisUnserialize(decrypt(file_get_contents(base_path($path))));// decrypt、base_pathはlaravelのもの

シリアライズされた文字列はセキュリティ的な意味で気を付けたいので、ものによっては暗号化

使いどころの例

  • 複雑なオブジェクトを返すメソッドを持つ外部APIの公式ライブラリがある。
  • このオブジェクトを引数とするアプリ内のメソッドを作ってみたのでテストをしたい。
  • テストではテストのAPIでも叩きたくないが、ライブラリ使用しないで自力でオブジェクトを作るのが難しい。

上記のとき、開発用のAPIを叩いた際に取得できたオブジェクトをシリアライズしてテスト時にデシリアライズして使うようにしてみたり。

1
3
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
1
3