symfonydoctrinesymfony4

Custom base entity in Symfony 4


I am using Symfony 4 and with Doctrine where I have entities which have the same common attributes such as createdWhen, editedWhen, ...

What i would like to do is this:

Defining a kind of base entity that holds these common attributes and implements the setter and getter. And many entities which inherit from that base entity. The database fields should all be defined in the table of the respective sub entity (no super table or the like should be created in the db).

Example:

/**
 * @ORM\Entity(repositoryClass="App\Repository\BaseRepository")
 */
class Base
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=127, nullable=true)
     */
    private $createdWhen;

    // Getter and setter
    ...
}


/**
 * @ORM\Entity(repositoryClass="App\Repository\PersonRepository")
 */
class Person extends Base
{
    /**
     * @ORM\Column(type="string", length=127, nullable=true)
     */
    private $name;

    // Getter and setter
    ...
}

/**
 * @ORM\Entity(repositoryClass="App\Repository\CarRepository")
 */
class Car extends Base
{
    /**
     * @ORM\Column(type="string", length=127, nullable=true)
     */
    private $brand;

    // Setter and getter
    ...
}

This should create the tables "person" and "car" (each with id, created_when) but no table base.

I would still like to be able to use the bin/console make:migration for updating the database schema.

Is this kind of approach possible with Symfony 4? If yes how would I define the entities and what do I have to change in terms of configuration, etc.?


Solution

  • You are looking for entity inheritance

    Rewrite your code like so

    /** @MappedSuperclass */
    class Base
    {
    ...
    }
    

    In fact, this is a part of Doctrine, here is what an official documentation says

    A mapped superclass is an abstract or concrete class that provides persistent entity state and mapping information for its subclasses, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes.