我在上传文件时遵循documentation's advices,同时我也在使用Gaufrette fileSystem。
在文档中,文件的移动是在方法upload()内的文档实体(拥有文件的实体)中通过生命周期回调@PostPersist和@PostUpdate进行的。使用@PreRemove和@PostRemove,当实体被移除时,文件也会自动删除。
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Document
{
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getFile()->move($this->getUploadRootDir(), $this->path);
// check if we have an old image and delete
if (isset($this->temp)) {
unlink($this->getUploadRootDir().'/'.$this->temp);
$this->temp = null;
}
$this->file = null;
}
/**
* @ORM\PreRemove()
*/
public function storeFilenameForRemove()
{
$this->temp = $this->getAbsolutePath();
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if (isset($this->temp)) {
unlink($this->temp);
}
}使用Gaufrette,我必须使用方法$filesystem->write()来移动文件,但根据我的理解,将Gaufrette服务($filesystem)注入实体(或任何服务)都不是推荐的。
那么,实现这一目标的正确方法是什么呢?
发布于 2019-10-10 00:24:10
您需要使用Doctrine事件订阅者,如以下问题所述:How to Use Gaufrette and Symfony 3.0
https://stackoverflow.com/questions/33582429
复制相似问题