Symfony2 - extending a base entity class or not binding entities?

I have a symfony2 project that includes half a dozen core entity types. I use the Doctrine.

These objects have several identical fields, such as creatorId, Created, Update, Status and Title. At the moment, each entity is separately defined - so, of course, there is a lot of duplication of the base code (and db fields).

I learn OOP when I learn symfony2, so I feel for it here, but my question is this:

Is it considered best practice to keep each entity as an independent class? Or would it be preferable to create a new base class for common properties, and then, so that other objects extend the base object?

bonus question:

And if it’s actually better to create objects that inherit from the parent class, I can vaguely visualize two options:

1) the parent class is a fully mapped Doctrine object with its own table in the database, which we will call, oh, let me call it "nodes". Therefore, invoking the child will always include an additional relationship between the node table and the entity table of the Child content type.

2) the parent class is - um - an abstract class (?) That defines the general properties of other objects, but not having the actual presence of the database. Each child object implements common properties separately, so the database structure remains identical to my current setting, but when defining entities there is (presumably) less code duplication.

I am mainly looking for advice on a general matter - child entities that extend the base object or just separate entities. Not expecting anyone to explain a better implementation, although hints are welcome.

+7
symfony
source share
1 answer

I would create an abstract class of basic entities, and let your other objects extend it. For example:

abstract class AbstractEntity { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id */ protected $id; /** * @var \datetime $created * * @ORM\Column(type="datetime") */ private $created; /** * @var \datetime $updated * * @ORM\Column(type="datetime") */ private $updated; ... } 

Then each of your entities can expand this:

 class SomeEntity extends AbstractEntity { /** * @var string * * @ORM\Column(name="some_name", type="string", length=255) */ protected $something } 

Option 2 is correct - there would be no specific table for the abstract class in the database.

You can have other abstract classes that extend the base class, if required. For example, an AbstractVehicle object will extend the base object. If, for example, you would like all AbstractVehicle sub-objects (for example, Car, Van, etc.) in the same table (for example, "car"), you could use something like a discriminator card. This article on matching inheritance may be helpful.

+10
source share

All Articles