Table Inheritance with Symfony2
Finally getting to the namespaced world of Symfony2. I have been working on a site that would suit using the Table Inheritance provided with Doctrine2.
Parent Table Configuration
First we set up the topmost table. This is the very top parent and it holds the discriminator information for each of the child tables. The annotations at the top of this file setup the inheritance used for child classes. The configuration is included here, and the extends setup of the child class is all that is needed.
@ORMInheritanceType("JOINED")
InheritanceType is the type of join used. Two types that I would be using are JOINED and SINGLETABLE.
* SINGLETABLE :: Has all the fields defined by the parent and child classes inside the one database table. Unused fields are null.
* JOINED :: Joins a table so there only the defined rows of the class are used in the created database table. The parent and the child tables are individual in the database and returned with a JOIN query.
You can read more about the ‘pros’ and ‘cons’ for each type in the documentation.
@ORMDiscriminatorColumn(name="class_name", type="string")
DiscriminatorColumn is the column that is inserted into the parent table and used with the key value provided in DiscriminatorMap to retain the reference to which class the JOIN is used. In this case either content or othercontent_ will be recorded into the base_page.class_name
field.
@ORMDiscriminatorMap({
"content" = "Content",
"other_content" = "ManhattanBundleOtherBundleEntityFrontPage"
})
DiscriminatorMap is used as the value that determines which class the provided key maps to when displaying data. Note that you must include the namespace for classes outside the current Bundle.
Child Table Configuration
The child configuration is simple. Just include the extends call when setting us the class and add in the fields you need on the subsequent table.
Child From Another Table Configuration
Keep in mind when using the Inheritance from a different bundle that you will need to include the use before extends to make sure it is available.
Conclude
With the configuration handled on the parent table you should be right to run the migrations or schema:update and have the updates made.
amsross@gmail.com
James, this was exceptionally helpful and using this and some further research was able to use inheritance mapping to set up a really useful entity structure. The only issue that I feel is unresolved here is building the FormView. When you create the formBuilder and wish to add a collection to it, you must specify the exact type, which the base entity is not capable of filling in for. Do you have any suggestions on integrating a collection of entities with table inheritance into a FormView?
Diego
Nice and clean tks!
Grab
How about creating a form for Frontpage?