How do you extend an entity in Symfony2 like you used to be able to in Symfony 1?
Extending an entity is the way to go. In the Doctrine2 world, they talk about inheritance mapping. Here a code example. It defines a BaseEntity
then it is extendsed to create a BaseAuditableEntity
and finally there is a User
entity extending BaseAuditableEntity
. The trick is to use the @Orm\MappedSuperclass
annotation. This inheritance scheme will create a single table even if there is three entities in my relationships graph. This will then merge all properties into a single table. The table created will contains every property mapped through the relations, i.e. properties from BaseAuditableEntity and from User. Here the code examples:
Acme\WebsiteBundle\Entity\BaseEntity.php
namespace Acme\WebsiteBundle\Entity;use Doctrine\ORM\Mapping as Orm;/** * @Orm\MappedSuperclass */class BaseEntity {}
Acme\WebsiteBundle\Entity\BaseAuditableEntity.php
namespace Acme\WebsiteBundle\Entity;use Doctrine\ORM\Mapping as Orm;/** * @Orm\MappedSuperclass */class BaseAuditableEntity extends BaseEntity { private $createdBy; /** * @Orm\Column(type="datetime", name="created_at") */ private $createdAt; /** * @Orm\ManyToOne(targetEntity="User") * @Orm\JoinColumn(name="updated_by", referencedColumnName="id") */ private $updatedBy; /** * @Orm\Column(type="datetime", name="updated_at") */ private $updatedAt; // Setters and getters here}
Acme\WebsiteBundle\Entity\User.php
namespace Acme\WebsiteBundle\Entity;use Acme\WebsiteBundle\Entity\BaseAuditableEntity;use Doctrine\ORM\Mapping as Orm;/** * @Orm\Entity(repositoryClass="Acme\WebsiteBundle\Entity\Repository\UserRepository") * @Orm\Table(name="acme_user") */class User extends BaseAuditableEntity implements AdvancedUserInterface, \Serializable{ /** * @Orm\Id * @Orm\Column(type="integer") * @Orm\GeneratedValue */ private $id; /** * @Orm\Column(type="string", name="first_name") */ private $firstName; /** * @Orm\Column(type="string", name="last_name") */ private $lastName; /** * @Orm\Column(type="string", unique="true") */ private $email; // Other properties // Constructor // Setters and getters}
Here a link to the official inheritance mapping documentation of Doctrine 2.1: here
Hope this helps, don't hesitate to comment if you need more information.
Regards,
Matt