Josh
Josh

Reputation: 1281

Doctrine relation to any object (any class)

I'm creating an entity class which represents a MenuItem. This can have a one-to-one relation with any class implementing SluggableInterface.

As the MenuItem should be able to relate to any SluggableInterface class (existing and future), I cannot specify a normal doctrine relation as there isn't a specific related entity.

I've come up with some possible solutions, but they have drawbacks:

  1. Create an ObjectReference entity to hold the class name and id of the related object. This class would then have a getObject() method to construct and return the necessary object. The drawback here is you can't (cleanly, at least) access doctrine from within the entity.

  2. Create an object_reference type to convert the object to a string containing the class name and id. The issue again is accessing doctrine in the Type class to retrieve the object.

  3. I've not tried this one yet, but create a class listening to doctrine events, then checking for fields with a custom annotation, and do the Object->String and vice-versa conversion there.

Before I start investigating #3, does anyone know of a "proper" or alternative way to do this?

Upvotes: 0

Views: 252

Answers (1)

Josh
Josh

Reputation: 1281

I used the suggestion from @Cerad about using class table inheritance (mapped superclass was used previously).

As I have a class which most of my entities extend (BaseEntity), including those which implement SluggableInterface, I set up a relation in the MenuItem to an object of BaseEntity - this allows any subclass to be used too.

To make sure only instances of SluggableInterface are related, I type-hint in the setter (e.g. public function setRelatedEntity(SluggableInterface $entity)....

Upvotes: 0

Related Questions