Skip to content

Instantly share code, notes, and snippets.

@ClementDuez
Created December 17, 2012 12:54
Show Gist options
  • Save ClementDuez/4318088 to your computer and use it in GitHub Desktop.
Save ClementDuez/4318088 to your computer and use it in GitHub Desktop.
Class Image zf2 with doctrine
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM,
Doctrine\Common\Collections\ArrayCollection;
/**
* Description of Image
*
* @author dudu
*/
/**
* @ORM\Entity
* @ORM\Table(name="image")
* @ORM\HasLifecycleCallbacks
*/
class Image
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(
* type = "string",
* nullable = true,
* length = 255
* )
*/
public $nom;
/**
* @ORM\Column(
* type = "string",
* length = 255,
* nullable = true
* )
*/
public $path;
/**
*/
public $file;
public function getId()
{
return $this->id;
}
public function getNom()
{
return $this->nom;
}
public function setNom($nom)
{
$this->nom = $nom;
}
public function getPath()
{
return $this->path;
}
public function setPath($path)
{
$this->path = $path;
}
public function getFile()
{
return $this->file;
}
public function setFile($file)
{
$this->file = $file;
}
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
}
public function getUploadRootDir()
{
return __DIR__.'/../../../../../public/'.$this->getUploadDir();
}
protected function getUploadDir()
{
return 'uploads/image/';
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
$guessExtension = explode('.', $this->file['name']);
$this->path = sha1(uniqid(mt_rand(), true)).'.'.$guessExtension[count($guessExtension)-1];
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
move_uploaded_file ($this->file['tmp_name'],$this->getUploadRootDir().$this->path);
unset($this->file);
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment