FOSRestbundle, JMS Serializer, and SonataMediaBundle return a public URL for the image

I am trying to return a JSON object ('Module') using the ManyToOne link to Sonata \ MediaBundle \ Entity via FOSRestBundle and JMS Serializer. How can I do it?

Here is the hack I made, but I don't think this is the best practice.

class Module { ... /** * @var Application\Sonata\MediaBundle\Entity\Media * * @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", inversedBy="module") * @ORM\JoinColumn(name="hero_image_id", referencedColumnName="id") * @JMS\Expose() */ private $heroImage; ... } class Media extends BaseMedia { ... /** * A Quick hack not the best method. * * @JMS\VirtualProperty * @JMS\SerializedName("url") * * @return string */ public function getUrlMethod() { global $kernel; $imageProvider = $kernel->getContainer()->get('sonata.media.provider.image'); return $imageProvider->generatePublicUrl($this, 'reference'); } ... } 

Thank you!

EDIT Thanks to Tautrimas Payarskas and the message he mentions. Here is the class.

 <?php namespace AXO\APIBundle\Listener\Serialization; use JMS\DiExtraBundle\Annotation\Service; use JMS\DiExtraBundle\Annotation\Tag; use JMS\DiExtraBundle\Annotation\Inject; use JMS\DiExtraBundle\Annotation\InjectParams; use JMS\Serializer\EventDispatcher\EventSubscriberInterface; use JMS\Serializer\EventDispatcher\ObjectEvent; use JMS\Serializer\GraphNavigator; /** * Add data after serialization * * @Service("axo.listener.serializationlistener") * @Tag("jms_serializer.event_subscriber") */ class SerializationListener implements EventSubscriberInterface { /** * @inheritdoc */ static public function getSubscribedEvents() { return array( array('event' => 'serializer.post_serialize', 'class' => 'Application\Sonata\MediaBundle\Entity\Media', 'method' => 'onPostSerialize'), ); } public function onPostSerialize(ObjectEvent $event) { global $kernel; $imageProvider = $kernel->getContainer()->get('sonata.media.provider.image'); $event->getVisitor()->addData('url',$imageProvider->generatePublicUrl($event->getObject(), 'reference')); } } 
+8
jms jmsserializerbundle symfony-sonata
source share
1 answer

You might want to see Add Extra Fields using the JMS Serializer package , as it has an example of how to add extra fields to serialized data that depend on external classes.

+2
source share

All Articles