Using DRY concept in Symfony2 Entities
5 minutes read
A way to make a Symfony2 app a bit more DRY when its entities are mapped with Doctrine ORM.
Mapped entities often share attributes, like id and timestamps. To follow DRY, you can put those in a base entity and have every other entity extend it. Here are two entities that repeat the same attributes.
An entity is just a PHP class.
User and Address look like this:
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="app_user")
*/
class User {
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* @ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
...
// getter setters
}
And Address:
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="app_address")
*/
class Address {
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(name="property", type="string", length=255)
*/
private $property;
/**
* @ORM\Column(name="street", type="string", length=255)
*/
private $street;
/**
* @ORM\Column(name="town", type="string", length=255)
*/
private $town;
/**
* @ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
...
// getter setters
}
Both have id, createdAt and updatedAt. We'll move those into a new BaseEntity class that the other entities extend.
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\MappedSuperclass
*/
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;
...
// getters setters
The @ORM\MappedSuperclass annotation at the top makes sure its attributes are mapped in the entities that extend it. Now remove those attributes from User and Address and have them extend BaseEntity.
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="app_user")
*/
class User extends BaseEntity {
/**
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @ORM\Column(name="email", type="string", length=255)
*/
private $email;
...
// getter setters
}
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="app_address")
*/
class Address extends BaseEntity {
/**
* @ORM\Column(name="property", type="string", length=255)
*/
private $property;
/**
* @ORM\Column(name="street", type="string", length=255)
*/
private $street;
/**
* @ORM\Column(name="town", type="string", length=255)
*/
private $town;
...
// getter setters
}
The entities already look cleaner, and with the shared attributes in one place we can build on them.
Next, set createdAt and updatedAt automatically before a record is persisted or updated. We'll use the @ORM\PrePersist and @ORM\PreUpdate annotations on two methods, plus @ORM\HasLifecycleCallbacks on the class.
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\HasLifecycleCallbacks
* @ORM\MappedSuperclass
*/
class BaseEntity {
...
/**
* @ORM\PrePersist
*/
public function setTimestamps() {
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedTimestamp() {
$this->updatedAt = new \DateTime();
}
...
The method names, setTimestamps and setUpdatedTimestamp, can be anything you like. The first sets createdAt and updatedAt just before a new record is persisted. We set them as DateTime objects and Doctrine converts them to the right database format. The second updates only updatedAt whenever a record is updated.
From now on, any entity that extends
BaseEntitygets a primary key (id) and timestamps for free.
More helpers
Anything you add to BaseEntity is inherited by every entity that extends it. For example, you could add a save method so the persistence logic lives there instead of in a controller. Right now, creating a user in a controller looks like this:
<?php
...
$user = new User();
$user->setName('Foo');
$user->setEmail('foo@bar.co');
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
...
Add this helper to BaseEntity and the persist and flush calls become a single save:
<?php namespace Foo\Bar\Entity;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\HasLifecycleCallbacks
* @ORM\MappedSuperclass
*/
class BaseEntity {
...
/**
* Helper method
*
* @param Doctrine\ORM\EntityManager $em
* @throws \RunTimeException
* @return void
*/
public function save(EntityManager $em) {
if (!$em instanceof EntityManager) {
throw new \RunTimeException(
sprintf('Expected an instance of Doctrine\ORM\EntityManager but got "%s"', gettype($em)), 400
);
}
$em->persist($this);
$em->flush();
}
...
It has to be public so the controller can call it. Pass it the entity manager:
<?php
...
$user = new User();
$user->setName('Foo');
$user->setEmail('foo@bar.co');
$em = $this->getDoctrine()->getEntityManager();
$user->save($em);
...
...
$addr = new Address();
$addr->setProperty('123');
$addr->setStreet('Foo Road');
$addr->setTown('Fondon');
$addr->save($em);
...
The full BaseEntity class is on a Gist. Suggestions for improvements are welcome.