首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Symfony中上传文件时,使用Gaufrette的优雅方式是什么?

在Symfony中上传文件时,使用Gaufrette的优雅方式是什么?
EN

Stack Overflow用户
提问于 2015-11-07 19:50:38
回答 1查看 184关注 0票数 1

我在上传文件时遵循documentation's advices,同时我也在使用Gaufrette fileSystem。

在文档中,文件的移动是在方法upload()内的文档实体(拥有文件的实体)中通过生命周期回调@PostPersist和@PostUpdate进行的。使用@PreRemove和@PostRemove,当实体被移除时,文件也会自动删除。

代码语言:javascript
复制
/**
 * @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)注入实体(或任何服务)都不是推荐的。

那么,实现这一目标的正确方法是什么呢?

EN

回答 1

Stack Overflow用户

发布于 2019-10-10 00:24:10

您需要使用Doctrine事件订阅者,如以下问题所述:How to Use Gaufrette and Symfony 3.0

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33582429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档