Search code examples
phpsymfonydoctrine-orm

Convert Entity to array in Symfony


I'm trying to get a multi-dimensional array from an Entity.

Symfony Serializer can already convert to XML, JSON, YAML etc. but not to an array.

I need to convert because I want have a clean var_dump. I now have entity with few connections and is totally unreadable.

How can I achieve this?


Solution

  • You can actually convert doctrine entities into an array using the built in serializer. I actually just wrote a blog post about this today: https://skylar.tech/detect-doctrine-entity-changes-without/

    You basically call the normalize function and it will give you what you want:

    $entityAsArray = $this->serializer->normalize($entity, null);
    

    I recommend checking my post for more information about some of the quirks but this should do exactly what you want without any additional dependencies or dealing with private/protected fields.