Skip to content

Instantly share code, notes, and snippets.

@sunvisor
Created March 12, 2019 23:47
Show Gist options
  • Save sunvisor/855a165690568c0a2ea923eb0d2d7c9b to your computer and use it in GitHub Desktop.
Save sunvisor/855a165690568c0a2ea923eb0d2d7c9b to your computer and use it in GitHub Desktop.

Entity を array に変換

serializer サービスを使う

<?php
$s = $container->get('serializer');
$r = $s->normalize($entity);
$json = $s->serialize($entity, 'json');

json へのシリアライズも簡単

ObjectNormalizer を使う

setIgnoreAttributes で、いらないフィールドを無視できる。

<?php
$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(array('staffId'));
$r = $normalizer->normalize($entity);

normalizer を直接使うと、Entity のフィールドがオブジェクト (例えば DateTime) だった場合にエラーになる。 この件は、 serializer と一緒に使うと解消する。

<?php
$normalizer = new ObjectNormalizer();
$serializer = new Serializer([$normalizer], []);
$r = $serializer->normalize($entity);

ただ、DateTime も配列に展開されてしまう。

setCallbacks で、フィールド毎の変換をさせることができる。

<?php
$callback = function($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('Y-m-d H:i:s')
        : '';
};
$normalizer = new ObjectNormalizer();
$normalizer->setCallbacks([
    'createdAt' => $callback,
    'updatedAt' => $callback
]);
$r = $normalizer->normalize($entity);

#symfony #doctrine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment