Last active
July 25, 2016 16:10
-
-
Save jabranr/e74b80958a997ffc62b8f8173b7a1e3e to your computer and use it in GitHub Desktop.
[POC DRY] BaseEntity class to be used as base for Entities in Symfony2.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Foo\Bar\Entity; | |
use Doctrine\ORM\EntityManager; | |
use Doctrine\ORM\Mapping as ORM; | |
/** | |
* BaseEntity | |
* | |
* @author Jabran Rafique <hello@jabran.me> | |
* @version 1.0.0 | |
* | |
* @ORM\MappedSuperclass | |
* @ORM\HasLifecycleCallbacks | |
*/ | |
class BaseEntity { | |
/** | |
* @ORM\Id | |
* @ORM\Column(name="id", type="integer") | |
* @ORM\GeneratedValue(strategy="AUTO") | |
*/ | |
private $id; | |
/** | |
* @ORM\Column(name="created_at", type="datetime") | |
*/ | |
private $createdAt; | |
/** | |
* @ORM\Column(name="updated_at", type="datetime") | |
*/ | |
private $updatedAt; | |
/** | |
* Helper method | |
* | |
* @param Doctrine\ORM\EntityManager $em | |
* @throws \RunTimeException | |
* @return void | |
*/ | |
protected function save(EntityManager $em) { | |
if (!$em instanceof EntityManager) { | |
throw new \RunTimeException('Entity Manager is required.', 400); | |
} | |
$em->persist($this); | |
$em->flush(); | |
} | |
/** | |
* @ORM\PrePersist | |
* | |
* {@inheritDoc} | |
*/ | |
public function setTimestamps() { | |
$this->setCreatedAt(new \DateTime); | |
$this->setUpdatedAt(new \DateTime); | |
} | |
/** | |
* @ORM\PreUpdate | |
* | |
* {@inheritDoc} | |
*/ | |
public function setUpdatedAtTimestamp() { | |
$this->setUpdatedAt(new \DateTime); | |
} | |
/** | |
* @codeCoverageIgnore | |
*/ | |
public function getId() { | |
return $this->id; | |
} | |
/** | |
* @codeCoverageIgnore | |
*/ | |
public function setId($id) { | |
$this->id = $id; | |
return $this; | |
} | |
/** | |
* @codeCoverageIgnore | |
*/ | |
public function getCreatedAt() { | |
return $this->createdAt; | |
} | |
/** | |
* @codeCoverageIgnore | |
*/ | |
public function setCreatedAt($createdAt) { | |
$this->createdAt = $createdAt; | |
return $this; | |
} | |
/** | |
* @codeCoverageIgnore | |
*/ | |
public function getUpdatedAt() { | |
return $this->updatedAt; | |
} | |
/** | |
* @codeCoverageIgnore | |
*/ | |
public function setUpdatedAt($updatedAt) { | |
$this->updatedAt = $updatedAt; | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment