TheNextBigThing
TheNextBigThing

Reputation: 335

Using Doctrine and Symfony to create Polymorphic like associations

I'm attempting to have an Fileable trait that will give provide an Entity with methods to CRUD Files based on the File Entity mentioned below.

After reading the documentation on Doctrine and searching the internet, the best I could find is Inheritance Mapping but these all require the subclass to extend the superclass which is not ideal as the current Entities already extend other classes. I could have FileFoo entity and a FileBar entity but this gets too messy and requires an extra join (super -> sub -> entity).

Alternatively, I could have a File Entity which has many columns for Entities (so foo_id for the Foo object, bar_id for the bar object and so on) but this gets messy and would require a new column for every entity that I'd want to add the Fileable trait too.

So to the questions: Am I thinking about how I want to hold data incorrectly? Is there some features/functions in Doctrine/Symfony that I've missed? Do you think I feature like this would be added if I were to fork Doctrine to add this feature, also where should I look?

<?php
/**
 * File
 *
 * @ORM\Table()
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
 */
class File
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue()
     */
    protected $id;
    /**
     * @var string
     *
     * @ORM\Column(type="string")
     */
    protected $entityName;
    /**
     * @var string
     *
     * @ORM\Column(type="string")
     */
    protected $entityId;
...

Upvotes: 8

Views: 586

Answers (2)

d.garanzha
d.garanzha

Reputation: 813

Take a look at embeddables or you could use traits.

Upvotes: 1

ABM_Dan
ABM_Dan

Reputation: 238

I accomplished a similar thing using Inheritance defined in traits, which alongside interfaces, basically gave me what a multiple extend would give.

Upvotes: 1

Related Questions