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.
- Get the Trait from this Gist. Save the file and set a suitable namespace.
- use the Trait in your Documents. Don’t forget to use it in Embedded Documents as well.
- 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
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.