Symfony 4 serialize entity wihout relations

前端 未结 3 1785
我寻月下人不归
我寻月下人不归 2021-01-05 20:35

I\'ve have to log changes of each entities. I\'ve Listener which listen for doctrine\'s events on preRemove, postUpdate and postDelete. My enity AccessModule has relations:<

相关标签:
3条回答
  • 2021-01-05 20:55

    ignored_attributes provides a quick, and easy way to accomplish what you're looking for.

    $serializer->serialize($object, 'json', ['ignored_attributes' => ['ignored_property']]); 
    

    Heres how its used with the serializer:

    use Acme\Person;
    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    use Symfony\Component\Serializer\Serializer;
    
    $person = new Person();
    $person->setName('foo');
    $person->setAge(99);
    
    $normalizer = new ObjectNormalizer();
    $encoder = new JsonEncoder();
    
    $serializer = new Serializer([$normalizer], [$encoder]);
    $serializer->serialize($person, 'json', ['ignored_attributes' => ['age']]); 
    

    Documentation: https://symfony.com/doc/current/components/serializer.html#ignoring-attributes

    0 讨论(0)
  • 2021-01-05 21:10

    Thing you are looking for is called serialization groups: here and here.

    Now let me explain how it works. It's quite simple. Say you have Post Entity:

    class Post
    {
        /**
         * @ORM\Id
         * @ORM\GeneratedValue
         * @ORM\Column(type="integer")
         * @Groups({"default"})
         */
        private $id;
    
        /**
         * @ORM\ManyToOne(targetEntity="App\Entity\User\User")
         * @Groups({"default"})
         */
        private $author;
    }
    

    And you have also User Entity:

    class User
    {
        /**
         * @ORM\Id
         * @ORM\GeneratedValue
         * @ORM\Column(type="integer")
         * @Groups({"default"})
         */
        private $id;
    
        /**
         * @ORM\Column(type="string", length=40)
         * @Groups({"default"})
         */
        private $firstName;
    
        /**
         * @ORM\Column(type="string", length=40)
         */
        private $lastName;
    }
    

    Post can have author(User) but I don't want to return all User data every single time. I'm interested only in id and first name.

    Take a closer look at @Groups annotation. You can specify so called serialization groups. It's nothing more than convinient way of telling Symfony which data you would like to have in your result set.

    You have to tell Symfony serializer which relationships you would like to keep by adding relevant groups in form of annotation above property/getter. You also have to specify which properties or getters of your relationships you would like to keep.

    Now how to let Symfony know about that stuff?

    When you prepare/configure your serializaition service you just simply have to provide defined groups like that:

    return $this->serializer->serialize($data, 'json', ['groups' => ['default']]);
    

    It's good to build some kind of wrapper service around native symfony serializer so you can simplify the whole process and make it more reusable.

    Also make sure that serializer is correctly configured - otherwise it will not take these group into account.

    That is also one way(among other ways) of "handling" circular references.

    Now you just need to work on how you will format your result set.

    0 讨论(0)
  • 2021-01-05 21:14

    Tested in Symfony 4.1, here is the documentation that actually works https://symfony.com/blog/new-in-symfony-2-7-serialization-groups

    Robert's explanation https://stackoverflow.com/a/48756847/579646 is missing the $classMetadataFactory in order to work. Here is my code:

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $encoders = [new JsonEncoder()];
        $normalizer = new ObjectNormalizer($classMetadataFactory);
        $normalizer->setCircularReferenceLimit(2);
        // Add Circular reference handler
        $normalizer->setCircularReferenceHandler(function ($object) {
            return $object->getId();
        });
        $normalizers = [$normalizer];
        $serializer = new Serializer($normalizers, $encoders);
        $jsonContent = $serializer->serialize($jobs, 'json', array('groups' => ['default']));
    
        return JsonResponse::fromJsonString($jsonContent);
    
    0 讨论(0)
提交回复
热议问题