Converting Doctrine MongoDB Document toJSON or toArray

This is a common need to convert Doctrine ODM Documents to simpler format. Generally we need to convert them to Array or serialized as JSON. And there are many ways to do it. So, here is my way, my simple Trait that simply works.

By useing this trait you’ll get 2 methods to convert your Document to Array or JSON. It will take care of embedded Documents too.

How to use?

3 simple steps.

  1. Get the Trait from this Gist. Save the file and set a suitable namespace.
  2. use the Trait in your Documents. Don’t forget to use it in Embedded Documents as well.
  3. If you need to hide some fields from serializing, mark them with setIgnoredFields function. In the document example above, the createdDate and secretFlag fields will not appear in converted Array or JSON.

You’re done! Now you can start using the cool converter functions.

A couple of points worth mentioning

If you got few more minutes, you may have a look at JMS Serializer. It’s a very sophisticated and more complex solution for serializing/deserializing. Also, Symfony has a good Serializer Component.

BTW, If you’re using an older version of PHP, older than 5.4, this solution is not for you as Trait is not there. However, I’ll strongly recommend you to upgrade.

3 Comments

Leave a Reply to Lou Chilcott Cancel reply

Your email address will not be published. Required fields are marked *