使用 LiipImagine 和 FOSRest 时想通过 API 返回绝对 url 时的常见问题
将 EE\TYSBundle 更改为您自己的代码,取自https://github.com/EE/TellYourStoryBundle/tree/develop
带有注入缓存管理器的 JMSSerializer 处理程序服务以获取正确的前缀
ee_tys.serializer.filename_handler:
class: EE\TYSBundle\Handler\FilenameHandler
arguments:
- "@liip_imagine.cache.manager"
tags:
- { name: 'jms_serializer.handler', type: Filename, format: json}
自定义文件名类型的处理程序
EE\TYSBundle\Handler\FilenameHandler.php
<?php
namespace EE\TYSBundle\Handler;
use EE\TYSBundle\Entity\Filename;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\VisitorInterface;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
class FilenameHandler implements SubscribingHandlerInterface
{
function __construct(CacheManager $manager)
{
$this->manager = $manager;
}
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'Filename',
'method' => 'serializeFilenameToJson',
),
);
}
public function serializeFilenameToJson(VisitorInterface $visitor, Filename $filename, array $type)
{
// `tile` is a name of Imagine filter you want to apply
return $this->manager->getBrowserPath($filename, 'tile', true);
}
}
EE\TYSBundle\Entity\文件名
<?php
namespace EE\TYSBundle\Entity;
/**
* Class Filename
* @package EE\TYSBundle\Entity
*/
class Filename {
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $extension;
public function __construct($filename)
{
$parts = explode(".", $filename);
$this->setName($parts[0]);
$this->setExtension($parts[1]);
}
/**
* @param mixed $extension
* @return Media
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* @return mixed
*/
public function getExtension()
{
return $this->extension;
}
/**
* @param mixed $name
* @return Filename
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @return string filename
*/
public function __toString()
{
return join(".", array($this->name, $this->extension));
}
}
自定义文件名类型的使用
/**
* @var string|null
*
* @ORM\Column(name="background_filename", type="string", length=255, nullable=true)
*
* @Serializer\Expose
* @Serializer\Type("Filename")
* @Serializer\SerializedName("background_uri")
*/
private $backgroundFilename;
从现在开始,您将获得带有绝对 URL 的 background_uri 到您的预览图像