问题
I have uploaded some images using the sonata-media-bundle, as suggested here
$media = new Media;
$media->setBinaryContent($file->getRealPath());
$media->setContext('myContext');
$media->setProviderName('sonata.media.provider.image');
$mediaManager->save($media);
Previous code creates the media correctly all files (according to context config) and db registry. Now what I did to delete the media is calling like this:
$media = $mediaManager->findOneBy(array('id' => $id));
$mediaManager->delete($media)
It correctly deletes the media data from database but not from the configured fileSystem, there are still some images associated to the uploaded media. I'm planning using the S3 filesystem so I need to delete all with the same framework
the most relevant of my sonata configuration (using the suggested too) is like this:
sonata_media:
default_context: default
db_driver: doctrine_orm
class:
media: MyApp\MediaBundle\Entity\Media
gallery: MyApp\MediaBundle\Entity\Gallery
gallery_has_media: MyApp\MediaBundle\Entity\GalleryHasMedia
contexts:
default:
providers:
- sonata.media.provider.youtube
- sonata.media.provider.image
- sonata.media.provider.file
formats:
small: { width: 200, quality: 77}
myContext:
providers:
- sonata.media.provider.image
formats:
normal: { width: 350, quality: 75}
tmb: { width: 100, quality: 75}
filesystem:
local:
directory: %kernel.root_dir%/../web/uploads/media
create: false
Thanks in advance.
回答1:
To be able to correctly delete all media related to the uploaded file, one has to use the appropiate provider:
from the sonata media documentation
A provider class is responsible for handling common things related to a media asset:
- thumbnails
- path
- editing the media with a form
- storing the media information (metadata)
So the code would look like:
$media = $mediaManager->findOneBy(array('id' => $id));
//assuming you have access through $this->get to the service container
$provider = $this->get($media->getProviderName());
$provider->removeThumbnails($media);
$mediaManager->delete($media)
来源:https://stackoverflow.com/questions/25942476/how-to-correctly-delete-all-images-uploaded-using-sonata-media-bundle