1

I am following the documentation's advices on file upload and I'm using Gaufrette fileSystem at the same time.

In the documentation, the file's moving is made inside the Document entity (the entity owning the file) within the method upload(), through Lifecycle callbacks @PostPersist and @PostUpdate. With @PreRemove and @PostRemove, the file is also automatically deleted when the entity is removed.

/**
 * @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);
    }
}

With Gaufrette, I have to use method $filesystem->write() to move the file, but injecting the Gaufrette service ($filesystem) into the entity (or any service) isn't recommended from what I could understand.

So what would be the correct way to achieve this?

Roubi
  • 1,989
  • 1
  • 27
  • 36

1 Answers1

0

You need to use Doctrine Event Subscribers as described on this question: How to Use Gaufrette and Symfony 3.0

numediaweb
  • 16,362
  • 12
  • 74
  • 110