8
我試圖通過FOSRestBundle和JMS序列化程序將帶有ManyToOne鏈接的JSON對象('Module')返回到Sonata \ MediaBundle \ Entity。我應該怎麼做呢?FOSRestbundle,JMS序列化程序和SonataMediaBundle返回公共圖像的url
這是我做的一個破解,但不認爲這是最好的做法。
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');
}
...
}
謝謝!
編輯 感謝Tautrimas Pajarskas和他提到的帖子。 這是班級。
<?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'));
}
}
而在services.yml你會註冊服務這種方式: '服務: AXO.listener.serializationlistener: 類:AXO \ APIBundle \監聽\系列化\ SerializationListener 標籤: - {名稱:jms_serializer.event_subscriber ,event:serializer.post_serialize,method:onPostSerialize}' – Vaseltior
爲什麼不爲圖像提供者獲取$ event-> getObject() - > getProviderName()的提供者而不是硬編碼? – ppetermann