Php 在使用Liip Imagine Bundle(和Symfony3)删除文件之前,请检查文件是否存在于缓存中
看起来非常基本:我想在删除Liip Imagine Bundle缓存之前检查它是否存在。例如:在照片更新后,删除了所有缓存,只重新生成了一些缩略图(例如175px但不是250px),我想删除相应的照片。 我在Symfony中使用了一个监听器,就像我看到的其他人一样。下面是它的外观:Php 在使用Liip Imagine Bundle(和Symfony3)删除文件之前,请检查文件是否存在于缓存中,php,listener,symfony,liipimaginebundle,Php,Listener,Symfony,Liipimaginebundle,看起来非常基本:我想在删除Liip Imagine Bundle缓存之前检查它是否存在。例如:在照片更新后,删除了所有缓存,只重新生成了一些缩略图(例如175px但不是250px),我想删除相应的照片。 我在Symfony中使用了一个监听器,就像我看到的其他人一样。下面是它的外观: <?php namespace AppBundle\EventListener; use Doctrine\ORM\Event\LifecycleEventArgs; use AppBundle\Entity
<?php
namespace AppBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\Photo;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Description of CachePhotoListener
*
* @author Norman
*/
class CachePhotoListener
{
protected $cacheManager;
protected $request;
public function __construct($cacheManager, RequestStack $request_stack)
{
$this->cacheManager = $cacheManager;
$this->request = $request_stack->getCurrentRequest();
}
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof Photo) {
$this->cacheManager->remove($entity->userPath());
}
}
// Case : remove photo
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$filters = array('thumb_prospect_250', 'thumb_prospect_175');
foreach($filters as $filter){
if ($entity instanceof Photo) {
$expectedCachePath = $this->cacheManager->getBrowserPath($entity->getPath(), $filter);
if (file_exists($expectedCachePath)) {
$this->cacheManager->resolve($this->request, $entity->getPath(), $filter);
$this->cacheManager->remove($entity->getPath());
}
}
}
}
我做错了什么?(我还尝试使用“is_readable”检查文件,并获得相同的结果)我想在需要目录路径时调用
$this->cacheManager->getBrowserPath
您在
$entity->getPath()中存储了什么?也许您可以自己检查文件是否存在于%kernel.cache\u dir%”
目录中。好的,我设法解决了我的问题。我修改了两件事。
首先,我使用isStored方法检查Liip缓存中是否存在照片。其次,我的cacheManager->resolve参数中有一个错误,$this->request参数不应该在那里
这为我提供了侦听器中的以下preRemove函数:
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$filters = array('thumb_prospect_250', 'thumb_prospect_175');
foreach($filters as $filter){
if ($entity instanceof Photo) {
$cacheExists = $this->cacheManager->isStored($entity->getPath(), $filter);
if ($cacheExists) {
$this->cacheManager->resolve($entity->getPath(), $filter);
$this->cacheManager->remove($entity->getPath());
}
}
}
}
$entity->getPath()返回一个相对url,如下所示:“uploads/photos/1/13CF43E720B12BDCAFF8A002E046E186559CDC0.jpg”同时,我找到了一个解决方案,但您如何准确地检查文件是否存在“%kernel.cache_dir%”?
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$filters = array('thumb_prospect_250', 'thumb_prospect_175');
foreach($filters as $filter){
if ($entity instanceof Photo) {
$cacheExists = $this->cacheManager->isStored($entity->getPath(), $filter);
if ($cacheExists) {
$this->cacheManager->resolve($entity->getPath(), $filter);
$this->cacheManager->remove($entity->getPath());
}
}
}
}