我正在使用liipimaginebundle,除了在更新原始图像时删除和更新缓存图像之外,一切正常。我想知道我该怎么做
config.yml
liip_imagine:
resolvers:
default:
web_path: ~
filter_sets:
cache: ~
travel_75_55:
quality: 80
filters:
thumbnail: { size: [75, 55], mode: outbound }
travel_270_161:
quality: 75
filters:
thumbnail: { size: [270, 161], mode: outbound}
这是实体:图片
/**
* Image
*
* @ORM\HasLifecycleCallbacks
*/
class Image
{
//.................
public $file;
public function setFile($file)
{
$this->file = $file;
if (null !== $this->url) {
$this->tempFilename = $this->url;
$this->url = null;
$this->alt = null;
}
}
public function getFile()
{
return $this->file;
}
private $tempFilename;
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null === $this->file) {
return;
}
$this->url = $this->file->guessExtension();
$this->alt = $this->file->getClientOriginalName();
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
if (null !== $this->tempFilename) {
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
$this->file->move(
$this->getUploadRootDir(),
$this->id.'.'.$this->url
);
}
/**
* @ORM\PreRemove()
*/
public function preRemoveUpload()
{
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if (file_exists($this->tempFilename)) {
unlink($this->tempFilename);
}
}
public function getUploadDir()
{
return 'uploads/img/travels';
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath()
{
return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}
}
答案 0 :(得分:6)
这是一个工作正常的解决方案
services:
project.cacheimage_listener:
class: Project\DashboardBundle\Listener\CacheImageListener
arguments: ["@liip_imagine.cache.manager"]
tags:
- { name: doctrine.event_listener, event: postUpdate }
- { name: doctrine.event_listener, event: preRemove }
创建监听器
namespace Project\DashboardBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Project\DashboardBundle\Entity\Image;
class CacheImageListener
{
protected $cacheManager;
public function __construct($cacheManager)
{
$this->cacheManager = $cacheManager;
}
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof Image) {
// clear cache of thumbnail
$this->cacheManager->remove($entity->getUploadDir());
}
}
// when delete entity so remove all thumbnails related
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof Image) {
$this->cacheManager->remove($entity->getWebPath());
}
}
}