Symfony 4 - LiipImagine - 侦听器删除我所有的目录(缓存清除侦听器)

我有一个 symfony 4 项目,它的用户实体与 Avatar 实体有关系(使用 VichUploaderBundle 上传的图像)。


在 Avatar.php 中:


/**

 * @ORM\Column(type="string", length=255, nullable=true)

 */

private $imageName;


/**

 * NOTE: This is not a mapped field of entity metadata, just a simple property.

 * 

 * @Assert\Image(

 *  mimeTypes="image/jpeg")

 * @Vich\UploadableField(mapping="avatar", fileNameProperty="imageName", size="imageSize")

 * 

 * @var File|null

 */

private $imageFile;

在 User.php 中:


/**

 * @ORM\OneToOne(targetEntity="App\Entity\Avatar", mappedBy="user", cascade={"persist", "remove"})

 */

private $avatar;

我有一个个人资料页面来编辑用户的数据(姓名、姓氏、邮件、头像)。在这个页面中,我使用 LiipImagineBundle 在某个维度显示当前头像。


当用户编辑他的个人资料时,我希望听众可以检查头像是否有变化。在这种情况下,它会删除旧的媒体/缓存。


所以我为此创建了一个监听器:


<?php


namespace App\Listener;


use App\Entity\Avatar;

use Doctrine\Common\EventSubscriber;

use Doctrine\ORM\Event\LifecycleEventArgs;

use Doctrine\ORM\Event\PreUpdateEventArgs;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;

use Symfony\Component\HttpFoundation\File\UploadedFile;

use Vich\UploaderBundle\Templating\Helper\UploaderHelper;


class ImageCacheSubscriber implements EventSubscriber

{


    /**

     * CacheManager

     *

     * @var CacheManager

     */

    private $cacheManager;


    /**

     * UploaderHelper

     *

     * @var UploaderHelper

     */

    private $uploaderHelper;


    public function __construct(CacheManager $cacheManager, UploaderHelper $uploaderHelper)

    {

        $this->cacheManager = $cacheManager;

        $this->uploaderHelper = $uploaderHelper;

    }


    public function getSubscribedEvents()

    {

        return [

            'preRemove',

            'preUpdate'

        ];

    }


    public function preRemove(LifecycleEventArgs $args)

    {


        $entity = $args->getEntity();

        if (!$entity instanceof Avatar) {

            return;

        }


        $this->cacheManager->remove($this->uploaderHelper->asset($entity, 'imageFile'));

    }


心有法竹
浏览 151回答 2
2回答

qq_笑_17

您可以收听事件,而不是收听 Doctrinevich_uploader.pre_remove事件。这将确保您获得每次都需要删除的旧图像。首先,确保您的 VichUploader 配置设置为在更新和删除时删除文件。这是默认设置。# config/packages/vich_uploader.yamlvich_uploader:&nbsp; &nbsp; mappings:&nbsp; &nbsp; &nbsp; &nbsp; avatar:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; upload_destination: '%kernel.project_dir%/public/uploads/avatar'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uri_prefix: 'uploads/avatar'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete_on_update: true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete_on_remove: true现在您需要创建侦听器。// src/EventListener/ImageCacheSubscriber.phpnamespace App\EventListener;use Liip\ImagineBundle\Imagine\Cache\CacheManager;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Vich\UploaderBundle\Event\Event;use Vich\UploaderBundle\Event\Events;use Vich\UploaderBundle\Storage\StorageInterface;class ImageCacheSubscriber implements EventSubscriberInterface{&nbsp; &nbsp; private $storage;&nbsp; &nbsp; private $cacheManager;&nbsp; &nbsp; public function __construct(StorageInterface $storage, CacheManager $cacheManager)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->storage = $storage;&nbsp; &nbsp; &nbsp; &nbsp; $this->cacheManager = $cacheManager;&nbsp; &nbsp; }&nbsp; &nbsp; public function onRemove(Event $event)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $path = $this->storage->resolveUri($event->getObject(), $event->getMapping()->getFilePropertyName());&nbsp; &nbsp; &nbsp; &nbsp; $this->cacheManager->remove($path);&nbsp; &nbsp; }&nbsp; &nbsp; public static function getSubscribedEvents()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return [Events::PRE_REMOVE => 'onRemove'];&nbsp; &nbsp; }}当移除任何 VichUploader 资产时,此侦听器将尝试将其从所有过滤器的缓存中移除。CacheManager::remove()如果您愿意,可以在方法中指定特定的过滤器。您也可以通过检查$event->getObject().这也对您的 LiipImagine 配置做出了一些假设。如果您使用默认的加载器和缓存解析器,这应该可以工作。如果您使用自定义加载器或解析器,您可能需要根据需要修改此侦听器。# config/packages/liip_imagine.yamlliip_imagine:&nbsp; &nbsp; resolvers:&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; web_path:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; web_root: '%kernel.project_dir%/public'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache_prefix: 'media/cache'&nbsp; &nbsp; loaders:&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filesystem:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data_root:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; - '%kernel.project_dir%/public'&nbsp; &nbsp; filter_sets:&nbsp; &nbsp; &nbsp; &nbsp; cache: ~&nbsp; &nbsp; &nbsp; &nbsp; # Your filters...如果您使用的是 Symfony Flex,那么您就完成了。否则,请确保将侦听器注册为服务。# config/services.yamlservices:&nbsp; &nbsp; # ...&nbsp; &nbsp; App\EventListener\ImageCacheSubscriber:&nbsp; &nbsp; &nbsp; &nbsp; arguments: ['@vich_uploader.storage.file_system', '@liip_imagine.cache.manager']&nbsp; &nbsp; &nbsp; &nbsp; tags:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; - { name: kernel.event_subscriber }

30秒到达战场

当您使用 VichUploaderBundle 时,不需要创建自己的侦听器。确保正确配置了生命周期事件,并且 Vich 应该负责删除旧图像。# config/packages/vich_uploader.yaml or app/config/config.ymlvich_uploader:&nbsp; &nbsp; db_driver: orm&nbsp; &nbsp; mappings:&nbsp; &nbsp; &nbsp; &nbsp; product_image:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uri_prefix: /images/products&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; upload_destination: '%kernel.project_dir%/public/images/products'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inject_on_load: false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete_on_update: true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete_on_remove: truehttps://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md#step-3-configure-the-lifecycle-events-optional-step
打开App,查看更多内容
随时随地看视频慕课网APP