Witam,
w aplikacji Symfony mam encję "Post", której jednym z elementów jest grafika i możliwość jest uploadowania. Grafika po załadowaniu zapisuje się do folderu "images" w web/uploads. Ustawiłem że w momencie aktualizacji grafiki stara grafika zostaje usunięta i zastępuje ją nowa. Próbuję dodać, aby w momencie usunięcia całego wpisu ("Post") usunięta została również grafika z katalogu web/uploads/images. I nie wiem, gdzie robię błąd.
Mam następujący kod:
/**
* @ORM\Entity
* @ORM\Table(name="post")
* @ORM\HasLifecycleCallbacks
*/
class Post {
const UPLOAD_DIR = 'uploads/images/';
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=80, nullable=true)
*/
private $image = null;
/**
* @var UploadedFile
*
*/
private $imageFile;
private $imageTemp;
/**
* @ORM\Column(type="datetime", nullable = true)
*/
private $updateDate;
[...]
/**
* Set image
*
* @param string $image
*
* @return Post
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* @return string
*/
public function getImage()
{
return Post::UPLOAD_DIR.$this->image;
}
public function getImageFile() {
return $this->imageFile;
}
public function setImageFile(UploadedFile $imageFile) {
$this->imageFile = $imageFile;
$this->updateDate = new \DateTime();
return $this;
}
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function preSave(){
if(null !== $this->getImageFile()){
if(null !== $this->image){
$this->imageTemp = $this->image;
}
$imageName = sha1(uniqid(null, true));
$this->image = $imageName.'.'.$this->getImageFile()->guessExtension();
}
$this->updateDate = new \DateTime();
}
/**
* @ORM\PostPersist
* @ORM\PostUpdate
*/
public function postSave(){
if(null !== $this->getImageFile()){
$this->getImageFile()->move($this->getUploadRootDir(), $this->image);
unset($this->imageFile);
if(null !== $this->imageTemp){
unlink($this->getUploadRootDir().$this->imageTemp);
unset($this->imageTemp);
}
}
}
/**
* @ORM\PostRemove
*/
public function postRemove(){
if(null !== $this->image){
unlink($this->getUploadRootDir().$this->image);
unset($this->image);
}
}
protected function getUploadRootDir(){
return __DIR__.'/../../../../web/'.Post::UPLOAD_DIR;
}
}
Podczas aktualizacji grafiki usuwanie działa, ale podczas usuwania postu grafika dalej zostaje w katalogu.
Z góry dziękuję za wszelką pomoc.