如何从SonataMediaBundle的图库中获取图像网址,以便与FOSRestBundle一起使用?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从SonataMediaBundle的图库中获取图像网址,以便与FOSRestBundle一起使用?相关的知识,希望对你有一定的参考价值。

我正在开发一个移动应用程序,它必须显示来自服务器的房屋图像。我为后端安装了Symfony2,FOSRestBundle和Sonata Media Bundle。

为了获得房屋图片网址,我为名为Property的实体配置了FOSRestBundle,该实体具有图库字段。这是REST控制器

class PropertiesController extends FOSRestController
{

    public function getPropertiesAction()
    {
        $response = $this->getDoctrine()->getRepository('ComissionBundle:Property')->findAll();
        if ($response == null){
            return "No properties";
        }
        else{
            return $response;
        }

    }

}

但我明白了:

[  
   {  
      "id":2,
      "name":"test",
      "city":"test",
      "address":"test",
      "sector":"test",
      "area":0,
      "rooms":112343,
      "price":0,
      "gallery":{  
         "context":"default",
         "name":"test",
         "enabled":false,
         "updated_at":"2016-08-26T17:18:51+0200",
         "created_at":"2016-08-26T17:18:51+0200",
         "default_format":"default_small",
         "id":1
      }
   }
]

如您所见,没有媒体对象。

然后,我尝试使用自定义存储库方法:

class PropertyRepository extends EntityRepository
{
    public function findMainInfoElements($elements)
    {
        $em = $this->getEntityManager();

        $queryText  = "SELECT u, g, h FROM ComissionBundle:Property u JOIN u.gallery g JOIN g.galleryHasMedias h";

        $query = $em->createQuery($queryText);

        return $query->setMaxResults($elements)->getResult();
    }
}

但结果是一样的。

如何从图库中获取网址以便在移动应用中显示这些网址? (特别是Sonata Media Bundle生成的拇指图像,这对于应用程序性能更好)

答案

我想你应该在PropertyRepository查询中加入galleryHasMedia实体和Media实体,但这还不够。您还应该为Media实体创建自定义序列化处理程序。

声明序列化处理程序

myapp.serialization.media_handler:
    class: PathToYourAppSerializerMediaSerializationHandler
    tags:
        - { name: jms_serializer.handler, type: PathToYourMediaEntityMedia, direction: serialization, format: json, method: serializeMedia }
    arguments: [ @sonata.media.provider.image, @sonata.media.provider.file ]

创建序列化处理程序

<?php

namespace CamelotSocialApiBundleSerializer;

use PathToYourMediaEntityMedia;

use JMSSerializerJsonSerializationVisitor;
use JMSSerializerContext;
use SonataMediaBundleProviderImageProvider;
use SonataMediaBundleProviderFileProvider;

class MediaSerializationHandler
{
    /**
     * @var ImageProvider
     */
    private $imageProvider;

    /**
     * @var FileProvider
     */
    private $fileProvider;

    public function __construct(ImageProvider $imageProvider, FileProvider $fileProvider)
    {
        $this->imageProvider = $imageProvider;
        $this->fileProvider = $fileProvider;
    }

    public function serializeMedia(JsonSerializationVisitor $visitor, Media $media, array $type, Context $context)
    {

        switch ($media->getProviderName()) {
            case 'sonata.media.provider.file':
                $serialization = $this->serializeFile($media);
                break;

            case 'sonata.media.provider.image':
                $serialization = $this->serializeImage($media);
                break;

            default:
                throw new RuntimeException("Serialization media provider not recognized");
        }

        if ($visitor->getRoot() === null) {
            $visitor->setRoot($serialization);
        }

        return $serialization;
    }

    private function serializeImage(Media $media)
    {
        // here you can provide one ore more URLs based on your SonataMedia configuration
        // you can also add some more properties coming from the media entity based on your needs (e.g. authorName, description, copyright etc)
        return [
            "url" => [
                "orig" => $this->imageProvider->generatePublicUrl($media, "reference"),
                "small" => $this->imageProvider->generatePublicUrl($media, "default_small"),
                "big" => $this->imageProvider->generatePublicUrl($media, "default_big"),
            ]
        ];
    }

    private function serializeFile(Media $media)
    {
        return [
            "name" => $media->getName(),
            "size" => $media->getSize(),
            "url" => $this->fileProvider->generatePublicUrl($media, 'reference')
        ];
    }
}

以上是关于如何从SonataMediaBundle的图库中获取图像网址,以便与FOSRestBundle一起使用?的主要内容,如果未能解决你的问题,请参考以下文章

Sonata Media Bundle - 如何按 ID 获取图像或画廊

SonataMediaBundle - 如何上传图片?

SonataMediaBundle - 如何使用自定义文件输入

如何使用 SonataMediaBundle 在树枝中获取图像路径?

使用 SonataMediaBundle,我如何找出可用的媒体提供商?

使用 SonataMediaBundle 上传到 AmazonS3