LoginSignup
0
0

ダンプをPHPで返すよ、"VarExporter"

Last updated at Posted at 2023-12-22

Symfony Component Advent Calendar 2023の23日目の記事です。

ダンプをPHPで返すよ、"VarExporter"

VarExporterは、渡されたデータをダンプしますが、返す値はPHPコードになります。

インストール

composer require symfony/var-exporter --dev

使い方

use Symfony\Component\VarExporter\VarExporter;

$result = VarExporter::export(['a' => 'b', 'c' => 123]);
echo $result;
/*
[
    'a' => 'b',
    'c' => 123,
]
*/

$item = new Item(name: '商品', price: 100);
$result = VarExporter::export($item);
echo $result;
/*
\Symfony\Component\VarExporter\Internal\Hydrator::hydrate(
    $o = [
        clone (\Symfony\Component\VarExporter\Internal\Registry::$prototypes['App\\Entity\\Item'] ?? \Symfony\Component\VarExporter\Internal\Registry::p('App\\Entity\\Item')),
    ],
    null,
    [
        'App\\Entity\\Item' => [
            'name' => [
                '商品',
            ],
            'price' => [
                100,
            ],
        ],
    ],
    $o[0],
    []
)
*/

Instantiator

この機能を使って、コンストラクターを使わずにオブジェクトを作成できます。

use Symfony\Component\VarExporter\Instantiator;

// Instantiatorでオブジェクト生成
$item = Instantiator::instantiate(Item::class, ['name' => '商品’, 'price' => 100]);
dump($item);
/*
^ App\Entity\Item^ {
  -name: "商品"
  -price: 100
}
*/

Hydorator

すでにインスタンス化されたオブジェクトのプロパティ設定ができます。privateなプロパティでもSetterメソッドを使わずにセットできます。

use Symfony\Component\VarExporter\Hydrator;

$item = new Item();
// Hydratorでプロパティ設定
Hydrator::hydrate($item, ['name' => '商品', 'price' => 200]);
dump($item);
/*
^ App\Entity\Item^ {
  -name: "商品"
  -price: 200
}
*/

まとめ

今回はVarExporterの紹介でした。すごいのはわかるんだけど、使い方がちょっと浮かばない。。
でも、きっといろいろなコンポーネントで活躍してるんだろうなとは思いました。(Doctrineとか)

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