Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
[POC DRY] BaseEntity class to be used as base for Entities in Symfony2.
<?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