2

I have in my Symfony 2.1 RC app a simple Comment model (using Doctrine 2). Every comment has a user and a message.

Currently, the CommentBundle manages comments on articles. I'd like it to be more generic to be able to comment any kind of entity without copying code across different bundles dedicated to comments...

For this to work, I also need a way to reference any entity from the comment one. I think having two fields entity_type and entity_id can be a nice solution. However, I can't get the object from these without mapping entity_type to classes manually and using the find method.

So how do I reference an entity from a comment ? And how can I create generic behavior working on several entities ?

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
Cydonia7
  • 3,744
  • 2
  • 23
  • 32

1 Answers1

3

You can create a abstract base class entity called Commentable and create entities that inherit Commentable such as Document or Post.

Since Document and Post are derived from Commentable, you can create a one to many relationship between the entities Commentable and Comment respectively.

Make sure to include in your base class ORM annotations for inheritance:

@InheritanceType
@DiscriminatorColumn
@DiscriminatorMap

Examples can be found on Doctrine Project Inheritance Documentation

Hyunmin Kim
  • 931
  • 2
  • 8
  • 18
  • Is there a way to allow multiple generic behaviours like this using this way ? For instance, if I want a Document to be Commentable and Taggable ? – Cydonia7 Aug 28 '12 at 20:06
  • PHP will not let you create multiple inheritance relationships directly. However you can use the magic function __call() to work around this. Here is an example. http://stackoverflow.com/questions/356128/can-i-extend-a-class-using-more-than-1-class-in-php – Hyunmin Kim Aug 29 '12 at 02:40
  • Right but Doctrine can't recognize a Document as both Taggable and Commentable ? – Cydonia7 Aug 29 '12 at 09:10
  • Correct. Doctrine won't recognize it. However, another way you can achieve this is through multiple level inheritance by making Taggable extend Commentable and make the rest of your entities extend Commentable. If there's very little need to make Taggable and Commentable seperate entities, you might want to consider just merging them into one entity. – Hyunmin Kim Aug 29 '12 at 15:35
  • And what if I've got a User class that already uses a DiscriminatorMap? I want to make both the entities Order and all User types (Customer, Admin, Editor) commentable. In that case inheritance doesn't seem an option. – Rvanlaak Mar 02 '13 at 16:37