Cydonia7
Cydonia7

Reputation: 3826

Generic comment system in Symfony2

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 ?

Upvotes: 2

Views: 1004

Answers (1)

Hyunmin Kim
Hyunmin Kim

Reputation: 971

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

Upvotes: 3

Related Questions